文章18 | 阅读 10876 | 点赞0
本章的例子,请参考我翻译的博文:itext7学习笔记——第6章,里面有详细的解释,有什么不懂得也可以评论或者私信我!
我们读取一个带有图片的PDF文档,生成新的文档,文档里面的内容是第一页缩小后的页面,第二页原始大小,第三页为放大后的页面,代码如下:
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import java.io.File;
import java.io.IOException;
public class C06E01_TheGoldenGateBridge_Scale_Shrink {
public static final String SRC = "src/main/resources/pdf/the_golden_gate_bridge.pdf";
public static final String DEST = "results/chapter06/the_golden_gate_bridge_scale_shrink.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E01_TheGoldenGateBridge_Scale_Shrink().createPdf(SRC, DEST);
}
public void createPdf(String src, String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument origPdf = new PdfDocument(new PdfReader(src));
//Original page size
PdfPage origPage = origPdf.getPage(1);
Rectangle orig = origPage.getPageSizeWithRotation();
//Add A4 page
PdfPage page = pdf.addNewPage(PageSize.A4.rotate());
//Shrink original page content using transformation matrix
PdfCanvas canvas = new PdfCanvas(page);
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(page.getPageSize().getWidth() / orig.getWidth(), page.getPageSize().getHeight() / orig.getHeight());
canvas.concatMatrix(transformationMatrix);
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
canvas.addXObject(pageCopy, 0, 0);
//Add page with original size
pdf.addPage(origPage.copyTo(pdf));
//Add A2 page
page = pdf.addNewPage(PageSize.A2.rotate());
//Scale original page content using transformation matrix
canvas = new PdfCanvas(page);
transformationMatrix = AffineTransform.getScaleInstance(page.getPageSize().getWidth() / orig.getWidth(), page.getPageSize().getHeight() / orig.getHeight());
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
pdf.close();
origPdf.close();
}
}
我们读取一个带有图片的PDF文档,把源文件分为4片,显示在新的文档的前4页,代码如下:
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import java.io.File;
import java.io.IOException;
public class C06E02_TheGoldenGateBridge_Tiles {
public static final String SRC = "src/main/resources/pdf/the_golden_gate_bridge.pdf";
public static final String DEST = "results/chapter06/the_golden_gate_bridge_tiles.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E02_TheGoldenGateBridge_Tiles().createPdf(SRC, DEST);
}
public void createPdf(String src, String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument sourcePdf = new PdfDocument(new PdfReader(src));
//Original page
PdfPage origPage = sourcePdf.getPage(1);
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
//Original page size
Rectangle orig = origPage.getPageSize();
//Tile size
Rectangle tileSize = PageSize.A4.rotate();
// Transformation matrix
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(tileSize.getWidth() / orig.getWidth() * 2f, tileSize.getHeight() / orig.getHeight() * 2f);
//The first tile
PdfPage page = pdf.addNewPage(PageSize.A4.rotate());
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, -orig.getHeight() / 2f);
//The second tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);
//The third tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
//The fourth tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, 0);
pdf.close();
sourcePdf.close();
}
}
我们读取一个带有图片的PDF文档,读取第一页的内容,然后在新的文档的第一页中显示4份同样的内容,代码如下:
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import java.io.File;
import java.io.IOException;
public class C06E03_TheGoldenGateBridge_N_up {
public static final String SRC = "src/main/resources/pdf/the_golden_gate_bridge.pdf";
public static final String DEST = "results/chapter06/the_golden_gate_bridge_nup.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E03_TheGoldenGateBridge_N_up().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument sourcePdf = new PdfDocument(new PdfReader(SRC));
//Original page
PdfPage origPage = sourcePdf.getPage(1);
//Original page size
Rectangle orig = origPage.getPageSize();
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
//N-up page
PageSize nUpPageSize = PageSize.A4.rotate();
PdfPage page = pdf.addNewPage(nUpPageSize);
PdfCanvas canvas = new PdfCanvas(page);
//Scale page
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(nUpPageSize.getWidth() / orig.getWidth() / 2f, nUpPageSize.getHeight() / orig.getHeight() / 2f);
canvas.concatMatrix(transformationMatrix);
//Add pages to N-up page
canvas.addXObject(pageCopy, 0, orig.getHeight());
canvas.addXObject(pageCopy, orig.getWidth(), orig.getHeight());
canvas.addXObject(pageCopy, 0, 0);
canvas.addXObject(pageCopy, orig.getWidth(), 0);
pdf.close();
sourcePdf.close();
}
}
我们读取两个PDF文件,把两个PDF文件拼接起来,代码如下:
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.utils.PdfMerger;
import java.io.File;
import java.io.IOException;
public class C06E04_88th_Oscar_Combine {
public static final String SRC1 = "src/main/resources/pdf/88th_reminder_list.pdf";
public static final String SRC2 = "src/main/resources/pdf/88th_noms_announcement.pdf";
public static final String DEST = "results/chapter06/88th_oscar_combined_documents.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E04_88th_Oscar_Combine().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document with output intent
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);
//Add pages from the first document
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());
//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());
firstSourcePdf.close();
secondSourcePdf.close();
pdf.close();
}
}
我们读取两个PDF文件,把两个PDF文件的特定页面拼接起来,代码如下:
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class C06E05_88th_Oscar_CombineXofY {
public static final String SRC1 = "src/main/resources/pdf/88th_reminder_list.pdf";
public static final String SRC2 = "src/main/resources/pdf/88th_noms_announcement.pdf";
public static final String DEST = "results/chapter06/88th_oscar_combined_documents_xy_pages.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E05_88th_Oscar_CombineXofY().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document with output intent
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);
//Add pages from the first document
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.merge(firstSourcePdf, Arrays.asList(1, 5, 7, 1));
//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.merge(secondSourcePdf, Arrays.asList(1, 15));
firstSourcePdf.close();
secondSourcePdf.close();
pdf.close();
}
}
我们读取两个PDF文件,把两个PDF文件的特定页面拼接起来,并添加目录,代码如下:
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.property.Property;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.property.TabAlignment;
import com.itextpdf.layout.property.TextAlignment;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class C06E06_88th_Oscar_Combine_AddTOC {
public static final String SRC1 = "src/main/resources/pdf/88th_noms_announcement.pdf";
public static final String SRC2 = "src/main/resources/pdf/oscars_movies_checklist_2016.pdf";
public static final String DEST = "results/chapter06/88th_oscar_the_revenant_nominations_TOC.pdf";
public static final Map<String, Integer> TheRevenantNominations = new TreeMap<String, Integer>();
static {
TheRevenantNominations.put("Performance by an actor in a leading role", 4);
TheRevenantNominations.put("Performance by an actor in a supporting role", 4);
TheRevenantNominations.put("Achievement in cinematography", 4);
TheRevenantNominations.put("Achievement in costume design", 5);
TheRevenantNominations.put("Achievement in directing", 5);
TheRevenantNominations.put("Achievement in film editing", 6);
TheRevenantNominations.put("Achievement in makeup and hairstyling", 7);
TheRevenantNominations.put("Best motion picture of the year", 8);
TheRevenantNominations.put("Achievement in production design", 8);
TheRevenantNominations.put("Achievement in sound editing", 9);
TheRevenantNominations.put("Achievement in sound mixing", 9);
TheRevenantNominations.put("Achievement in visual effects", 10);
}
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E06_88th_Oscar_Combine_AddTOC().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document document = new Document(pdfDoc);
document.add(new Paragraph(new Text("The Revenant nominations list"))
.setTextAlignment(TextAlignment.CENTER));
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
for (Map.Entry<String, Integer> entry : TheRevenantNominations.entrySet()) {
//Copy page
PdfPage page = firstSourcePdf.getPage(entry.getValue()).copyTo(pdfDoc);
pdfDoc.addPage(page);
//Overwrite page number
Text text = new Text(String.format("Page %d", pdfDoc.getNumberOfPages() - 1));
text.setBackgroundColor(Color.WHITE);
document.add(new Paragraph(text).setFixedPosition(
pdfDoc.getNumberOfPages(), 549, 742, 100));
//Add destination
String destinationKey = "p" + (pdfDoc.getNumberOfPages() - 1);
PdfArray destinationArray = new PdfArray();
destinationArray.add(page.getPdfObject());
destinationArray.add(PdfName.XYZ);
destinationArray.add(new PdfNumber(0));
destinationArray.add(new PdfNumber(page.getMediaBox().getHeight()));
destinationArray.add(new PdfNumber(1));
pdfDoc.addNamedDestination(destinationKey, destinationArray);
//Add TOC line with bookmark
Paragraph p = new Paragraph();
p.addTabStops(new TabStop(540, TabAlignment.RIGHT, new DottedLine()));
p.add(entry.getKey());
p.add(new Tab());
p.add(String.valueOf(pdfDoc.getNumberOfPages() - 1));
p.setProperty(Property.ACTION, PdfAction.createGoTo(destinationKey));
document.add(p);
}
firstSourcePdf.close();
//Add the last page
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
PdfPage page = secondSourcePdf.getPage(1).copyTo(pdfDoc);
pdfDoc.addPage(page);
//Add destination
PdfArray destinationArray = new PdfArray();
destinationArray.add(page.getPdfObject());
destinationArray.add(PdfName.XYZ);
destinationArray.add(new PdfNumber(0));
destinationArray.add(new PdfNumber(page.getMediaBox().getHeight()));
destinationArray.add(new PdfNumber(1));
pdfDoc.addNamedDestination("checklist", destinationArray);
//Add TOC line with bookmark
Paragraph p = new Paragraph();
p.addTabStops(new TabStop(540, TabAlignment.RIGHT, new DottedLine()));
p.add("Oscars\u00ae 2016 Movie Checklist");
p.add(new Tab());
p.add(String.valueOf(pdfDoc.getNumberOfPages() - 1));
p.setProperty(Property.ACTION, PdfAction.createGoTo("checklist"));
document.add(p);
secondSourcePdf.close();
// close the document
document.close();
}
}
我们读取带有表单两个PDF文件,把两个PDF文件拼接起来,代码如下:
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.kernel.pdf.*;
import java.io.File;
import java.io.IOException;
public class C06E07_Combine_Forms {
public static final String DEST = "results/chapter06/combined_forms.pdf";
public static final String SRC1 = "src/main/resources/pdf/subscribe.pdf";
public static final String SRC2 = "src/main/resources/pdf/state.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E07_Combine_Forms().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument destPdfDocument = new PdfDocument(new PdfWriter(dest));
PdfDocument[] sources = new PdfDocument[] {
new PdfDocument(new PdfReader(SRC1)),
new PdfDocument(new PdfReader(SRC2))
};
PdfPageFormCopier formCopier = new PdfPageFormCopier();
for (PdfDocument sourcePdfDocument : sources) {
sourcePdfDocument.copyPagesTo(
1, sourcePdfDocument.getNumberOfPages(),
destPdfDocument, formCopier);
sourcePdfDocument.close();
}
destPdfDocument.close();
}
}
我们读取带有表单的PDF文件,读取CSV,填充表单,拼接多个表单,代码如下:
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import java.io.*;
import java.util.Map;
import java.util.StringTokenizer;
public class C06E08_FillOutAndMergeForms {
public static final String DEST = "results/chapter06/fill_out_and_merge_forms.pdf";
public static final String SRC = "src/main/resources/pdf/state.pdf";
public static final String DATA = "src/main/resources/data/united_states.csv";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C06E08_FillOutAndMergeForms().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(dest));
PdfPageFormCopier formCopier = new PdfPageFormCopier();
BufferedReader bufferedReader = new BufferedReader(new FileReader(DATA));
String line;
boolean headerLine = true;
int i = 1;
while ((line = bufferedReader.readLine()) != null) {
if (headerLine) {
headerLine = false;
continue;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument sourcePdfDocument = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
//Rename fields
i++;
PdfAcroForm form = PdfAcroForm.getAcroForm(sourcePdfDocument, true);
form.renameField("name", "name_" + i);
form.renameField("abbr", "abbr_" + i);
form.renameField("capital", "capital_" + i);
form.renameField("city", "city_" + i);
form.renameField("population", "population_" + i);
form.renameField("surface", "surface_" + i);
form.renameField("timezone1", "timezone1_" + i);
form.renameField("timezone2", "timezone2_" + i);
form.renameField("dst", "dst_" + i);
//Fill out fields
StringTokenizer tokenizer = new StringTokenizer(line, ";");
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name_" + i).setValue(tokenizer.nextToken());
fields.get("abbr_" + i).setValue(tokenizer.nextToken());
fields.get("capital_" + i).setValue(tokenizer.nextToken());
fields.get("city_" + i).setValue(tokenizer.nextToken());
fields.get("population_" + i).setValue(tokenizer.nextToken());
fields.get("surface_" + i).setValue(tokenizer.nextToken());
fields.get("timezone1_" + i).setValue(tokenizer.nextToken());
fields.get("timezone2_" + i).setValue(tokenizer.nextToken());
fields.get("dst_" + i).setValue(tokenizer.nextToken());
sourcePdfDocument.close();
sourcePdfDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
//Copy pages
sourcePdfDocument.copyPagesTo(1, sourcePdfDocument.getNumberOfPages(), pdfDocument, formCopier);
sourcePdfDocument.close();
}
bufferedReader.close();
pdfDocument.close();
}
}
我们读取带有表单的PDF文件,读取CSV,填充表单,锁定表单,最后拼接多个表单,代码如下:
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import java.io.*;
import java.util.Map;
import java.util.StringTokenizer;
public class C06E09_FillOutFlattenAndMergeForms {
public static final String DEST1 = "results/chapter06/fill_out_flatten_forms_merge.pdf";
public static final String DEST2 = "results/chapter06/fill_out_flatten_forms_smart_merge.pdf";
public static final String SRC = "src/main/resources/pdf/state.pdf";
public static final String DATA = "src/main/resources/data/united_states.csv";
public static void main(String args[]) throws IOException {
File file = new File(DEST1);
file.getParentFile().mkdirs();
file = new File(DEST2);
file.getParentFile().mkdirs();
new C06E09_FillOutFlattenAndMergeForms().createPdf(DEST1, DEST2);
}
public void createPdf(String dest1, String dest2) throws IOException {
PdfDocument destPdfDocument = new PdfDocument(new PdfWriter(dest1));
//Smart mode
PdfDocument destPdfDocumentSmartMode = new PdfDocument(new PdfWriter(dest2).setSmartMode(true));
BufferedReader bufferedReader = new BufferedReader(new FileReader(DATA));
String line;
boolean headerLine = true;
while ((line = bufferedReader.readLine()) != null) {
if (headerLine) {
headerLine = false;
continue;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument sourcePdfDocument = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
//Read fields
PdfAcroForm form = PdfAcroForm.getAcroForm(sourcePdfDocument, true);
StringTokenizer tokenizer = new StringTokenizer(line, ";");
Map<String, PdfFormField> fields = form.getFormFields();
//Fill out fields
fields.get("name").setValue(tokenizer.nextToken());
fields.get("abbr").setValue(tokenizer.nextToken());
fields.get("capital").setValue(tokenizer.nextToken());
fields.get("city").setValue(tokenizer.nextToken());
fields.get("population").setValue(tokenizer.nextToken());
fields.get("surface").setValue(tokenizer.nextToken());
fields.get("timezone1").setValue(tokenizer.nextToken());
fields.get("timezone2").setValue(tokenizer.nextToken());
fields.get("dst").setValue(tokenizer.nextToken());
//Flatten fields
form.flattenFields();
sourcePdfDocument.close();
sourcePdfDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
//Copy pages
sourcePdfDocument.copyPagesTo(1, sourcePdfDocument.getNumberOfPages(), destPdfDocument, null);
sourcePdfDocument.copyPagesTo(1, sourcePdfDocument.getNumberOfPages(), destPdfDocumentSmartMode, null);
sourcePdfDocument.close();
}
bufferedReader.close();
destPdfDocument.close();
destPdfDocumentSmartMode.close();
}
}
本章代码可在如下地址下载(IDEA工程):iText7——第六章源代码工程
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/u012397189/article/details/78745027
内容来源于网络,如有侵权,请联系作者删除!