简体   繁体   English

尝试使用 iText7 合并合并 pdf,但是当我打开最终合并的 pdf 时,它说无法加载 pdf 文档

[英]Trying to merge pdfs using iText7 merger, but when I open final merged pdf it says failed to load pdf document

I'm creating two ByteArrayOutputStream using itext7 PdfWriter, and then merging them in one pdf using merger but when I try to open final merged pdf it says failed to load.我正在使用 itext7 PdfWriter 创建两个 ByteArrayOutputStream,然后使用合并将它们合并到一个 pdf 中,但是当我尝试打开最终合并的 pdf 时,它说加载失败。

@GetMapping(value = "/customers",
            produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<InputStreamResource> customersReport() throws IOException {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PdfDocument pdf = new PdfDocument(new PdfWriter(out));
    Document document = new Document(pdf);
    Paragraph p = new Paragraph("AAAAAAAAA");
    document.add(p);
    document.close();    

    ByteArrayOutputStream out1 = new ByteArrayOutputStream();
    PdfDocument pdf1 = new PdfDocument(new PdfWriter(out1));
    Document document1 = new Document(pdf1);
    Paragraph p1 = new Paragraph("123456A");
    document1.add(p1);
    document1.close();

    ByteArrayOutputStream outfinal = new ByteArrayOutputStream();
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outfinal));
    PdfMerger merger = new PdfMerger(pdfDoc);

    PdfDocument pdf2 = new PdfDocument(new PdfReader(new ByteArrayInputStream(out.toByteArray())));
    merger.merge(pdf2,1,pdf2.getNumberOfPages());

    PdfDocument pdf3 = new PdfDocument(new PdfReader(new ByteArrayInputStream(out1.toByteArray())));
    merger.merge(pdf3,1,pdf3.getNumberOfPages());

    ByteArrayInputStream bis = new ByteArrayInputStream(outfinal.toByteArray());

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "inline; filename=customers.pdf");

    return ResponseEntity
            .ok()
            .headers(headers)
            .contentType(MediaType.APPLICATION_PDF)
            .body(new InputStreamResource(bis));
}

You have to close the merger你必须关闭合并

merger.close();

before using its output in在使用其输出之前

ByteArrayInputStream bis = new ByteArrayInputStream(outfinal.toByteArray());

because only during closing the pdf file is completed.因为只有在关闭pdf文件时才完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM