简体   繁体   English

用Java合并2个PDF

[英]Merge 2 PDFs in Java

I have a Problem with iText and merging of 2PDFs to 1 PDF. 我在使用iText并将2PDF合并为1 PDF时遇到问题。

I would like to merge this PDFs: 我想合并以下PDF:

PDF1 - One Site: PDF1-一个站点:

This is PDF1. 这是PDF1。

PDF2 - One Site: PDF2-一个站点:

This is PDF2. 这是PDF2。

What I need: https://dl.dropboxusercontent.com/u/4001370/whatIneed.pdf 我需要什么: https : //dl.dropboxusercontent.com/u/4001370/whatIneed.pdf

Code 1 - Two Sites: 代码1-两个站点:

One Site One: This is PDF1. 一个站点一个:这是PDF1。
One Site Two: This is PDF2. 一个站点2:这是PDF2。

    PDFMergerUtility ut = new PDFMergerUtility();
    ut.addSource("C:\\Temp\\PDF1.pdf");
    ut.addSource("C:\\Temp\\PDF2.pdf");
    ut.setDestinationFileName("C:\\Temp\\Code1.pdf");
    ut.mergeDocuments();

Code 2 - The number is overwritten: 代码2-数字被覆盖:

This is PDF(1/2). 这是PDF(1/2)。

public class main {
public static void main(String[] args) throws IOException, DocumentException {
    PdfReader reader;
    PdfImportedPage page;


    LinkedList<File> fileList = new LinkedList<File>();
    fileList.add(new File("C:\\Temp\\PDF1.pdf"));
    fileList.add(new File("C:\\Temp\\PDF2.pdf"));


    File ergebnis = new File("C:\\Temp\\Code2.pdf");
    Document document2 = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document2, new FileOutputStream(ergebnis));

    document2.open();
    PdfContentByte canvas = writer.getDirectContent();

    // Header 
    reader = new PdfReader(fileList.get(0).getAbsolutePath());
    page = writer.getImportedPage(reader, 1);
    canvas.addTemplate(page, 0, 0);
    // Aufgabe
    reader = new PdfReader(fileList.get(1).getAbsolutePath());
    for(int i=1; i<=reader.getNumberOfPages(); i++){
        page = writer.getImportedPage(reader, i);
        canvas.addTemplate(page, 0, 0);
        document2.newPage();
    }

    document2.close();
    writer.close();
}

} }

I have no Idea. 我不知道。 I hope you can help me at this problem. 希望您能在这个问题上帮助我。

Please read Chapter 6 of my book. 请阅读我的书的第6章 It explains why using PdfWriter / PdfImportedPage is the wrong way to merge documents. 它解释了为什么使用PdfWriter / PdfImportedPage是合并文档的错误方法。 You should use PdfCopy or PdfSmartCopy if you want to concatenate two documents. 如果要串联两个文档,则应使用PdfCopyPdfSmartCopy You should use PdfStamper if you want one document to act as company stationery for the other document. 如果希望一个文档充当另一文档的公司信纸 ,则应使用PdfStamper From your question, it's not clear which one of both you need (you leave that open to interpretation), so please read chapter 6. I've done the effort of writing it and making available for free so that you can choose the solution that is right for you. 从您的问题出发,尚不清楚您需要两者中的哪一个(您可以公开解释),因此请阅读第6章。我已尽力编写并免费提供了它,以便您选择可以解决的方案。适合您

这个问题有点含糊-如果您要问如何获取两个PDF并将它们合并在一起,那么这篇SO文章展示了在iText中最简单的方法: 如何将不同的文档合并为一个文档?

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

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