使用 PDFBox 合并页面? [英] Use PDFBox to Merge Pages?

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

问题描述

我知道我可以使用 PDFBox 将多个 PDF 合并为一个 PDF.但是有没有办法合并页面?例如,我在 PDF 中有一个标题,并希望将其插入到组合 PDF 的第一页顶部并将所有内容向下推.有没有办法使用 PDFBox API 来做到这一点?

I know I can use PDFBox to merge multiple PDF's into one PDF. But is there a way to merge pages? For example, I have a header in PDF and want it to be inserted to the top of the first page of the combined PDF and push everything down. Is there a way to do it using PDFBox API?

推荐答案

下面是一些代码,用于将两个文件复制到一个合并的文件中,每个文件都有多个副本.它按页复制.这是我在回答这个问题时得到的信息:使用 PDFBox 复制 pdf 可以像使用 iText 一样小吗?

Here is some code that works to copy two files into a merged one with multiple copies of each one. It copies by pages. It's something I got using the information in the answer to this question: Can duplicating a pdf with PDFBox be small like with iText?

所以你所要做的就是只复制 doc1 的第一页,只复制 doc2 的所有页面.有一条评论,您必须进行更改才能留下一些页面.

So all you have to do is to make one copy only of the first page of doc1 and one copy only of all pages of doc2. There's a comment where you'll have to make a change to leave off some pages.

final int COPIES = 1; // total copies

// Same code as linked answer mostly
PDDocument samplePdf = new PDDocument();

InputStream in1 = this.getClass().getResourceAsStream(DOC1_NAME);
PDDocument doc1 = PDDocument.load(in1);
List<PDPage> pages = (List<PDPage>) doc1.getDocumentCatalog().getAllPages();

// *** Change this loop to only copy the pages you want from DOC1

for (PDPage page : pages) {
    for (int i = 0; i < COPIES; i++) { // loop for each additional copy
        samplePdf.importPage(page);
    }
}

// Same code again mostly
InputStream in2 = this.getClass().getResourceAsStream(DOC2_NAME);
PDDocument doc2 = PDDocument.load(in2);
pages = (List<PDPage>) doc2.getDocumentCatalog().getAllPages();
for (PDPage page : pages) {
    for (int i = 0; i < COPIES; i++) { // loop for each additional copy
        samplePdf.importPage(page);
    }
}

// Then write the results out
File output = new File(OUT_NAME);
FileOutputStream out = new FileOutputStream(output);
samplePdf.save(out);

samplePDF.close();

in1.close();
doc1.close();
in2.close();
doc2.close();

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

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