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

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

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

private void printMore(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        String masterPath = req.getServletContext().getRealPath("/assets/template/templateStatement.pdf");
        try (PdfReader reader = new PdfReader(masterPath);
             ZipOutputStream zipFile = new ZipOutputStream(resp.getOutputStream());
             PdfWriter writer = new PdfWriter(zipFile);
             PdfDocument pdf = new PdfDocument(reader, writer);
             Document doc = new Document(pdf)) {

            List<Student> studentList = getFactoryDAO().getStatementDAO().selectStudentHasBalance();
            for (Student student : studentList){

                // Generate PDF for the student

                PdfPage page = pdf.getPage(1);
                PdfCanvas canvas = new PdfCanvas(page);

                FontProgram fontProgram = FontProgramFactory.createFont();
                PdfFont font = PdfFontFactory.createFont(fontProgram, "utf-8", true);
                canvas.setFontAndSize(font, 10);

                canvas.beginText();

                canvas.setTextMatrix(178, 650); // student code
                canvas.showText(student.getS_Code());

                canvas.setTextMatrix(200, 610); // Date of Statement
                canvas.showText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

                canvas.endText();

                float[] pointsWidth = {60f,120f,70f,70f};
                Table table = new Table(pointsWidth);
                table.setMarginTop(280);
                table.setMarginLeft(70);
                table.setFont(font);
                table.setFontSize(10);
                table.setTextAlignment(TextAlignment.CENTER);
                //Header Table
                table.addCell(new Cell().add("Date Inscription"));
                table.addCell(new Cell().add("Name"));
                table.addCell(new Cell().add("Fees"));
                table.addCell(new Cell().add("Observation"));
                //Detail Table
                table.addCell(new Cell().add(student.getTxnDate()));
                table.addCell(new Cell().add(student.getS_FullName));
                table.addCell(new Cell().add(student.getFees));
                table.addCell(new Cell().add(student.getObservation));

                doc.add(table);

                ZipEntry zipEntry = new ZipEntry(student.getS_Code() + "_" + student.getS_LName() + ".pdf");
                zipFile.putNextEntry(zipEntry);
                //zipFile.write(); Shall I use it?

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        resp.setHeader("Content-disposition","attachement; filename=test.zip");
        resp.setContentType("application/zip");
    }

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

String masterPath = req.getServletContext().getRealPath("/assets/template/templateStatement.pdf");
        try (PdfReader reader = new PdfReader(masterPath);
             ZipOutputStream zipFile = new ZipOutputStream(resp.getOutputStream());
             PdfWriter writer = new PdfWriter(zipFile);
             PdfDocument pdf = new PdfDocument(reader, writer)
             ) {

            List<Student> studentList = getFactoryDAO().getStatementDAO().selectStudentHasBalance();
            for (Student student : studentList){

                try (Document doc = new Document(pdf)){
                       // Generate PDF for the student

                PdfPage page = pdf.getPage(1);
                PdfCanvas canvas = new PdfCanvas(page);

                FontProgram fontProgram = FontProgramFactory.createFont();
                PdfFont font = PdfFontFactory.createFont(fontProgram, "utf-8", true);
                canvas.setFontAndSize(font, 10);

                canvas.beginText();

                canvas.setTextMatrix(178, 650); // student code
                canvas.showText(student.getS_Code());

                canvas.setTextMatrix(200, 610); // Date of Statement
                canvas.showText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

                canvas.endText();

                float[] pointsWidth = {60f,120f,70f,70f};
                Table table = new Table(pointsWidth);
                table.setMarginTop(280);
                table.setMarginLeft(70);
                table.setFont(font);
                table.setFontSize(10);
                table.setTextAlignment(TextAlignment.CENTER);
                //Header Table
                table.addCell(new Cell().add("Date Inscription"));
                table.addCell(new Cell().add("Name"));
                table.addCell(new Cell().add("Fees"));
                table.addCell(new Cell().add("Observation"));
                //Detail Table
                table.addCell(new Cell().add(student.getTxnDate()));
                table.addCell(new Cell().add(student.getS_FullName));
                table.addCell(new Cell().add(student.getFees));
                table.addCell(new Cell().add(student.getObservation));

                doc.add(table);

                ZipEntry zipEntry = new ZipEntry(student.getS_Code() + "_" + student.getS_LName() + ".pdf");
                zipFile.putNextEntry(zipEntry);
                //zipFile.write(); Shall I use it?
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        resp.setHeader("Content-disposition","attachement; filename=test.zip");
        resp.setContentType("application/zip");

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

nxowjjhe

nxowjjhe1#

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

String masterPath = req.getServletContext().getRealPath("/assets/template/templateStatement.pdf");
        try (ZipOutputStream zipOut = new ZipOutputStream(resp.getOutputStream())) {

            Liste<File> listFile = new ArrayList<>();
            List<Student> studentList = getFactoryDAO().getStatementDAO().selectStudentHasBalance();
            for (Student student : studentList){

                File file = new File(student.getS_Code()+"_"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".pdf");
                try (PdfDocument pdf = new PdfDocument(new PdfReader(masterPath), new PdfWriter(file.getName()))
                     Document doc = new Document(pdf)){
                       // Generate PDF for the student

                PdfPage page = pdf.getPage(1);
                PdfCanvas canvas = new PdfCanvas(page);

                FontProgram fontProgram = FontProgramFactory.createFont();
                PdfFont font = PdfFontFactory.createFont(fontProgram, "utf-8", true);
                canvas.setFontAndSize(font, 10);

                canvas.beginText();

                canvas.setTextMatrix(178, 650); // student code
                canvas.showText(student.getS_Code());

                canvas.setTextMatrix(200, 610); // Date of Statement
                canvas.showText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

                canvas.endText();

                float[] pointsWidth = {60f,120f,70f,70f};
                Table table = new Table(pointsWidth);
                table.setMarginTop(280);
                table.setMarginLeft(70);
                table.setFont(font);
                table.setFontSize(10);
                table.setTextAlignment(TextAlignment.CENTER);
                //Header Table
                table.addCell(new Cell().add("Date Inscription"));
                table.addCell(new Cell().add("Name"));
                table.addCell(new Cell().add("Fees"));
                table.addCell(new Cell().add("Observation"));
                //Detail Table
                table.addCell(new Cell().add(student.getTxnDate()));
                table.addCell(new Cell().add(student.getS_FullName));
                table.addCell(new Cell().add(student.getFees));
                table.addCell(new Cell().add(student.getObservation));

                doc.add(table);

                listFile.add(file);
                }

            }

            File zipFile = createZip(listFile, 
            newSimpleDateFormat("yyyy-MM-dd").format(new Date())); //BenjaminD source in answer

            ZipEntry zipEntry = new ZipEntry(zipFile.getName);
            zipEntry.putNextEntry(zipEntry);
            fileInputStream fis = new FileInputStream(zipFile);
            byte[] bytes = new byte[1024];
            int length;
            while((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            fis.close();

            resp.setHeader("Content-disposition","attachement; filename=" + zipFile);
            resp.setContentType("application/zip");

        } catch (IOException e) {
            e.printStackTrace();
        }

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

cunj1qz1

cunj1qz12#

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

private File createZip(List<File> forZip, LocalDate date) {

    String zipName = Constants.ORDER_FILE_PATH + date.getYear() +"-" + date.getMonth().getValue() + "-" + date.getMonth().getDisplayName(TextStyle.FULL, Locale.FRENCH) + ".zip";

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(zipName);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        for (File srcFile : forZip) {
            FileInputStream fis = new FileInputStream(srcFile);
            ZipEntry zipEntry = new ZipEntry(srcFile.getName());
            zipOut.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            fis.close();
            //srcFile.delete();
        }
        zipOut.close();
        fos.close();
    } catch (IOException e) {
        logger.error("createZip", e);
    }

    return new File(zipName);
}

相关问题