【问题标题】:Trying to merge pdfs using iText7 merger, but when I open final merged pdf it says failed to load pdf document尝试使用 iText7 合并合并 pdf,但是当我打开最终合并的 pdf 时,它说加载 pdf 文档失败
【发布时间】:2020-04-07 09:08:08
【问题描述】:

我正在使用 itext7 PdfWriter 创建两个 ByteArrayOutputStream,然后使用 merge 将它们合并到一个 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));
}

【问题讨论】:

    标签: java spring spring-boot pdf itext7


    【解决方案1】:

    你必须关闭合并

    merger.close();
    

    在使用其输出之前

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

    因为只有在关闭pdf文件的过程中才会完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 2015-12-13
      相关资源
      最近更新 更多