将PDF文档和图像合并为一个PDF

时间:2017-10-10 10:11:15

标签: java pdf itext pdf-generation

我已阅读merging PDF documents section中的示例,但我无法为以下任务制定更优化的解决方案:

我想以任何顺序合并一系列PDF和图像文件(original post)。效率低下的原因是我需要使用PdfWriter为图像创建虚拟的1页PDF文件,然后使用PdfReader从字节数组中读取它。

问题:是否有更有效的方法(可能通过PdfCopy#addPage())?

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSmartCopy;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Helper class that creates PDF from given image(s) (JPEG, PNG, ...) or PDFs.
 */
public class MergeToPdf {

    public static void main(String[] args) throws IOException, DocumentException {
        if (args.length < 2) {
            System.err.println("At least two arguments are required: in1.pdf [, image2.jpg ...], out.pdf");
            System.exit(1);
        }

        Document mergedDocument = new Document();
        PdfSmartCopy pdfCopy = new PdfSmartCopy(mergedDocument, new FileOutputStream(args[args.length - 1]));
        mergedDocument.open();

        for (int i = 0; i < args.length - 1; i++) {
            PdfReader reader;

            if (args[i].toLowerCase().endsWith(".pdf")) {
                System.out.println("Adding PDF " + args[i] + "...");
                // Copy PDF document:
                reader = new PdfReader(args[i]);
            }
            else {
                System.out.println("Adding image " + args[i] + "...");

                final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

                final Document imageDocument = new Document();
                PdfWriter.getInstance(imageDocument, byteStream);

                imageDocument.open();

                // Create single page with the dimensions as source image and no margins:
                Image image = Image.getInstance(args[i]);
                image.setAbsolutePosition(0, 0);

                imageDocument.setPageSize(image);
                imageDocument.newPage();
                imageDocument.add(image);

                imageDocument.close();

                // Copy PDF document with only one page carrying the image:
                reader = new PdfReader(byteStream.toByteArray());
            }

            pdfCopy.addDocument(reader);
            reader.close();
        }

        mergedDocument.close();
    }
}

0 个答案:

没有答案