首页 文章

iText - 如何将页面添加到使用PdfCopy创建的文档中

提问于
浏览
7

我正在使用iText(特别是iTextSharp 4.1.6),我想通过组合现有PDF中的页面来创建PDF,还可以插入从图像创建的新页面 .

我分别使用PdfCopy和PdfWriter将这两部分分开工作 . 从图像创建页面的代码如下所示:

PdfWriter pw = PdfWriter.GetInstance(doc, outputStream);
Image img = Image.GetInstance(inputStream);
doc.Add(img);
doc.NewPage();

现在,由于PdfCopy继承自PdfWriter,我认为我可以使用相同的技术将这样的“图像页面”添加到我的PdfCopy对象,但它不起作用(如果你在上面的例子中实例化PdfCopy而不是PdfWriter) ,页面上没有任何内容) .

从快速查看源代码我注意到,当PdfCopy的contstructor调用超类构造函数时,它使用一个新的Document对象,而不是传入的对象,所以我想这就是原因 .

有没有更好的方法来解决这个问题?目前,我最好的猜测是使用PdfWriter从图像创建单页Pdf,然后使用PdfCopy将其添加到文档中,但这似乎是一种解决方法 .

1 回答

  • 9

    我最近有这个问题,这里的答案实际上并没有帮助 . 我的用例基本上是“获取一堆PDF和图像(.jpg,.png等)并将它们全部合并为1个PDF” . 我不得不使用PdfCopy,因为它保留了表单字段和标签之类的东西,而PdfWriter并不这样做 .

    基本上,因为PdfCopy不允许您使用addPage()创建新页面,所以您必须在内存中使用页面上的图像创建新的PDF,然后使用PdfCopy从该PDF中复制出页面 .

    例如:

    Document pdfDocument = new Document();
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(pdfDocument, pdfOutputStream);
    
        pdfDocument.open();
    
        for (File file : allFiles) {
           if (/* file is PDF */) {
               /* Copy all the pages in the PDF file into the new PDF */
               PdfReader reader = new PdfReader(file.getAllBytes());
               for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                  copy.addPage(copy.getImportedPage(reader, i);
               }
           } else {
               /* File is image. Create a new PDF in memory, write the image to its first page, and then use PdfCopy to copy that first page back into the main PDF */
               Document imageDocument = new Document();
               ByteArrayOutputStream imageDocumentOutputStream = new ByteArrayOutputStream();
               PdfWriter imageDocumentWriter = PdfWriter.getInstance(imageDocument, imageDocumentOutputStream);
    
                imageDocument.open();
    
                if (imageDocument.newPage()) {
    
                    image = Image.getInstance(file.getAllBytes());
    
                    if (!imageDocument.add(image)) {
                       throw new Exception("Unable to add image to page!");
                    }
    
                    imageDocument.close();
                    imageDocumentWriter.close();
    
                    PdfReader imageDocumentReader = new PdfReader(imageDocumentOutputStream.toByteArray());
    
                    copy.addPage(copy.getImportedPage(imageDocumentReader, 1));
    
                    imageDocumentReader.close();
             }
    
         }
    

相关问题