使用servlet和itext 7生成分组多个pdf的zip文件

nbnkbykc  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(519)

我尝试使用itext7将多个生成的pdf文件放入servlet的zip文件中,我已经成功地将一个pdf文件放入zip文件中,但没有更多。代码如下:

  1. private void printMore(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
  2. String masterPath = req.getServletContext().getRealPath("/assets/template/templateStatement.pdf");
  3. try (PdfReader reader = new PdfReader(masterPath);
  4. ZipOutputStream zipFile = new ZipOutputStream(resp.getOutputStream());
  5. PdfWriter writer = new PdfWriter(zipFile);
  6. PdfDocument pdf = new PdfDocument(reader, writer);
  7. Document doc = new Document(pdf)) {
  8. List<Student> studentList = getFactoryDAO().getStatementDAO().selectStudentHasBalance();
  9. for (Student student : studentList){
  10. // Generate PDF for the student
  11. PdfPage page = pdf.getPage(1);
  12. PdfCanvas canvas = new PdfCanvas(page);
  13. FontProgram fontProgram = FontProgramFactory.createFont();
  14. PdfFont font = PdfFontFactory.createFont(fontProgram, "utf-8", true);
  15. canvas.setFontAndSize(font, 10);
  16. canvas.beginText();
  17. canvas.setTextMatrix(178, 650); // student code
  18. canvas.showText(student.getS_Code());
  19. canvas.setTextMatrix(200, 610); // Date of Statement
  20. canvas.showText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  21. canvas.endText();
  22. float[] pointsWidth = {60f,120f,70f,70f};
  23. Table table = new Table(pointsWidth);
  24. table.setMarginTop(280);
  25. table.setMarginLeft(70);
  26. table.setFont(font);
  27. table.setFontSize(10);
  28. table.setTextAlignment(TextAlignment.CENTER);
  29. //Header Table
  30. table.addCell(new Cell().add("Date Inscription"));
  31. table.addCell(new Cell().add("Name"));
  32. table.addCell(new Cell().add("Fees"));
  33. table.addCell(new Cell().add("Observation"));
  34. //Detail Table
  35. table.addCell(new Cell().add(student.getTxnDate()));
  36. table.addCell(new Cell().add(student.getS_FullName));
  37. table.addCell(new Cell().add(student.getFees));
  38. table.addCell(new Cell().add(student.getObservation));
  39. doc.add(table);
  40. ZipEntry zipEntry = new ZipEntry(student.getS_Code() + "_" + student.getS_LName() + ".pdf");
  41. zipFile.putNextEntry(zipEntry);
  42. //zipFile.write(); Shall I use it?
  43. }
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. resp.setHeader("Content-disposition","attachement; filename=test.zip");
  48. resp.setContentType("application/zip");
  49. }

我已经根据这篇文章和这篇文章,但不工作。我已经查看了更多类似的帖子,但是itext7的版本没有前面提到的pdfwriter.getinstance。我试过更多的东西,但都没能做得更好。
更新时间:
在enterman建议之后,我更新了它如下:

  1. String masterPath = req.getServletContext().getRealPath("/assets/template/templateStatement.pdf");
  2. try (PdfReader reader = new PdfReader(masterPath);
  3. ZipOutputStream zipFile = new ZipOutputStream(resp.getOutputStream());
  4. PdfWriter writer = new PdfWriter(zipFile);
  5. PdfDocument pdf = new PdfDocument(reader, writer)
  6. ) {
  7. List<Student> studentList = getFactoryDAO().getStatementDAO().selectStudentHasBalance();
  8. for (Student student : studentList){
  9. try (Document doc = new Document(pdf)){
  10. // Generate PDF for the student
  11. PdfPage page = pdf.getPage(1);
  12. PdfCanvas canvas = new PdfCanvas(page);
  13. FontProgram fontProgram = FontProgramFactory.createFont();
  14. PdfFont font = PdfFontFactory.createFont(fontProgram, "utf-8", true);
  15. canvas.setFontAndSize(font, 10);
  16. canvas.beginText();
  17. canvas.setTextMatrix(178, 650); // student code
  18. canvas.showText(student.getS_Code());
  19. canvas.setTextMatrix(200, 610); // Date of Statement
  20. canvas.showText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  21. canvas.endText();
  22. float[] pointsWidth = {60f,120f,70f,70f};
  23. Table table = new Table(pointsWidth);
  24. table.setMarginTop(280);
  25. table.setMarginLeft(70);
  26. table.setFont(font);
  27. table.setFontSize(10);
  28. table.setTextAlignment(TextAlignment.CENTER);
  29. //Header Table
  30. table.addCell(new Cell().add("Date Inscription"));
  31. table.addCell(new Cell().add("Name"));
  32. table.addCell(new Cell().add("Fees"));
  33. table.addCell(new Cell().add("Observation"));
  34. //Detail Table
  35. table.addCell(new Cell().add(student.getTxnDate()));
  36. table.addCell(new Cell().add(student.getS_FullName));
  37. table.addCell(new Cell().add(student.getFees));
  38. table.addCell(new Cell().add(student.getObservation));
  39. doc.add(table);
  40. ZipEntry zipEntry = new ZipEntry(student.getS_Code() + "_" + student.getS_LName() + ".pdf");
  41. zipFile.putNextEntry(zipEntry);
  42. //zipFile.write(); Shall I use it?
  43. }
  44. }
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. resp.setHeader("Content-disposition","attachement; filename=test.zip");
  49. resp.setContentType("application/zip");

但还是没有运气。
欢迎你的帮助。

nxowjjhe

nxowjjhe1#

特别感谢benjamind、enterman和stack社区的支持。
我把这个答案贴在那些和我面临同样问题的人身上(我已经被困了4天了使用itext 7和Servlet生成多个pdf“
正如enterman所说:“需要新的文档示例”。此外还需要PDF文件。正如本雅明所说:“先生成一个pdf文件,然后把它们放进zip”。

  1. String masterPath = req.getServletContext().getRealPath("/assets/template/templateStatement.pdf");
  2. try (ZipOutputStream zipOut = new ZipOutputStream(resp.getOutputStream())) {
  3. Liste<File> listFile = new ArrayList<>();
  4. List<Student> studentList = getFactoryDAO().getStatementDAO().selectStudentHasBalance();
  5. for (Student student : studentList){
  6. File file = new File(student.getS_Code()+"_"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".pdf");
  7. try (PdfDocument pdf = new PdfDocument(new PdfReader(masterPath), new PdfWriter(file.getName()))
  8. Document doc = new Document(pdf)){
  9. // Generate PDF for the student
  10. PdfPage page = pdf.getPage(1);
  11. PdfCanvas canvas = new PdfCanvas(page);
  12. FontProgram fontProgram = FontProgramFactory.createFont();
  13. PdfFont font = PdfFontFactory.createFont(fontProgram, "utf-8", true);
  14. canvas.setFontAndSize(font, 10);
  15. canvas.beginText();
  16. canvas.setTextMatrix(178, 650); // student code
  17. canvas.showText(student.getS_Code());
  18. canvas.setTextMatrix(200, 610); // Date of Statement
  19. canvas.showText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  20. canvas.endText();
  21. float[] pointsWidth = {60f,120f,70f,70f};
  22. Table table = new Table(pointsWidth);
  23. table.setMarginTop(280);
  24. table.setMarginLeft(70);
  25. table.setFont(font);
  26. table.setFontSize(10);
  27. table.setTextAlignment(TextAlignment.CENTER);
  28. //Header Table
  29. table.addCell(new Cell().add("Date Inscription"));
  30. table.addCell(new Cell().add("Name"));
  31. table.addCell(new Cell().add("Fees"));
  32. table.addCell(new Cell().add("Observation"));
  33. //Detail Table
  34. table.addCell(new Cell().add(student.getTxnDate()));
  35. table.addCell(new Cell().add(student.getS_FullName));
  36. table.addCell(new Cell().add(student.getFees));
  37. table.addCell(new Cell().add(student.getObservation));
  38. doc.add(table);
  39. listFile.add(file);
  40. }
  41. }
  42. File zipFile = createZip(listFile,
  43. newSimpleDateFormat("yyyy-MM-dd").format(new Date())); //BenjaminD source in answer
  44. ZipEntry zipEntry = new ZipEntry(zipFile.getName);
  45. zipEntry.putNextEntry(zipEntry);
  46. fileInputStream fis = new FileInputStream(zipFile);
  47. byte[] bytes = new byte[1024];
  48. int length;
  49. while((length = fis.read(bytes)) >= 0) {
  50. zipOut.write(bytes, 0, length);
  51. }
  52. fis.close();
  53. resp.setHeader("Content-disposition","attachement; filename=" + zipFile);
  54. resp.setContentType("application/zip");
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }

它将把zip放在一个zip中(可以直接使用fileoutpustream将它放在一个zip中)。
再次感谢你。

展开查看全部
cunj1qz1

cunj1qz12#

您应该尝试使用fileinputstream,如下所示(我自己的代码,在生产中运行良好)

  1. private File createZip(List<File> forZip, LocalDate date) {
  2. String zipName = Constants.ORDER_FILE_PATH + date.getYear() +"-" + date.getMonth().getValue() + "-" + date.getMonth().getDisplayName(TextStyle.FULL, Locale.FRENCH) + ".zip";
  3. FileOutputStream fos = null;
  4. try {
  5. fos = new FileOutputStream(zipName);
  6. ZipOutputStream zipOut = new ZipOutputStream(fos);
  7. for (File srcFile : forZip) {
  8. FileInputStream fis = new FileInputStream(srcFile);
  9. ZipEntry zipEntry = new ZipEntry(srcFile.getName());
  10. zipOut.putNextEntry(zipEntry);
  11. byte[] bytes = new byte[1024];
  12. int length;
  13. while((length = fis.read(bytes)) >= 0) {
  14. zipOut.write(bytes, 0, length);
  15. }
  16. fis.close();
  17. //srcFile.delete();
  18. }
  19. zipOut.close();
  20. fos.close();
  21. } catch (IOException e) {
  22. logger.error("createZip", e);
  23. }
  24. return new File(zipName);
  25. }
展开查看全部

相关问题