用Java合并2个PDF [英] Merge 2 PDFs in Java

查看:166
本文介绍了用Java合并2个PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到iText问题并将2PDF合并为1个PDF。

I have a Problem with iText and merging of 2PDFs to 1 PDF.

我想合并这些PDF:

PDF1 - 一个站点:

PDF1 - One Site:


这是PDF1。

This is PDF1.

PDF2 - 一个站点:

PDF2 - One Site:


这是PDF2。

This is PDF2.

我需要的是: https:// dl.dropboxusercontent.com/u/4001370/whatIneed.pdf

代码1 - 两个网站:

Code 1 - Two Sites:


一个站点一:这是PDF1。

一个站点二:这是PDF2。

One Site One: This is PDF1.
One Site Two: This is 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();

代码2 - 数字被覆盖:

Code 2 - The number is overwritten:

这是PDF(1/2)。

This is 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.

推荐答案

请阅读第6章。它解释了为什么使用 PdfWriter / PdfImportedPage 是合并文档的错误方法。如果要连接两个文档,则应使用 PdfCopy PdfSmartCopy 。如果您希望一个文档作为另一个文档的公司信纸,则应使用 PdfStamper 。从您的问题来看,目前尚不清楚您需要哪一个(您可以解释),所以请阅读第6章。我已经完成了编写和免费提供的工作,以便您可以选择适合你。

Please read Chapter 6 of my book. It explains why using PdfWriter/PdfImportedPage is the wrong way to merge documents. You should use PdfCopy or PdfSmartCopy if you want to concatenate two documents. You should use PdfStamper if you want one document to act as company stationery for the other document. 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.

这篇关于用Java合并2个PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆