iText Jump-Start Tutorial : Chapter 6
c06e01_thegoldengatebridge_scale_shrink
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
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.addXObjectAt(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.addXObjectAt(pageCopy, 0, 0);
pdf.close();
origPdf.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Xobject;
namespace Tutorial.Chapter06 {
public class C06E01_TheGoldenGateBridge_Scale_Shrink {
public const String SRC = "../../../resources/pdf/the_golden_gate_bridge.pdf";
public const String DEST = "../../../results/chapter06/the_golden_gate_bridge_scale_shrink.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E01_TheGoldenGateBridge_Scale_Shrink().CreatePdf(SRC, DEST);
}
public virtual void CreatePdf(String src, String dest) {
//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.AddXObjectAt(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.AddXObjectAt(pageCopy, 0, 0);
pdf.Close();
origPdf.Close();
}
}
}
06e02_thegoldengatebridge_tiles
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
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.addXObjectAt(pageCopy, 0, -orig.getHeight() / 2f);
//The second tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObjectAt(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);
//The third tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObjectAt(pageCopy, 0, 0);
//The fourth tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObjectAt(pageCopy, -orig.getWidth() / 2f, 0);
pdf.close();
sourcePdf.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Xobject;
namespace Tutorial.Chapter06 {
public class C06E02_TheGoldenGateBridge_Tiles {
public const String SRC = "../../../resources/pdf/the_golden_gate_bridge.pdf";
public const String DEST = "../../../results/chapter06/the_golden_gate_bridge_tiles.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E02_TheGoldenGateBridge_Tiles().CreatePdf(SRC, DEST);
}
public virtual void CreatePdf(String src, String dest) {
//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.AddXObjectAt(pageCopy, 0, -orig.GetHeight() / 2f);
//The second tile
page = pdf.AddNewPage(PageSize.A4.Rotate());
canvas = new PdfCanvas(page);
canvas.ConcatMatrix(transformationMatrix);
canvas.AddXObjectAt(pageCopy, -orig.GetWidth() / 2f, -orig.GetHeight() / 2f);
//The third tile
page = pdf.AddNewPage(PageSize.A4.Rotate());
canvas = new PdfCanvas(page);
canvas.ConcatMatrix(transformationMatrix);
canvas.AddXObjectAt(pageCopy, 0, 0);
//The fourth tile
page = pdf.AddNewPage(PageSize.A4.Rotate());
canvas = new PdfCanvas(page);
canvas.ConcatMatrix(transformationMatrix);
canvas.AddXObjectAt(pageCopy, -orig.GetWidth() / 2f, 0);
pdf.Close();
sourcePdf.Close();
}
}
}
c06e03_thegoldengatebridge_n_up
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
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.addXObjectAt(pageCopy, 0, orig.getHeight());
canvas.addXObjectAt(pageCopy, orig.getWidth(), orig.getHeight());
canvas.addXObjectAt(pageCopy, 0, 0);
canvas.addXObjectAt(pageCopy, orig.getWidth(), 0);
pdf.close();
sourcePdf.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Xobject;
namespace Tutorial.Chapter06 {
public class C06E03_TheGoldenGateBridge_N_up {
public const String SRC = "../../../resources/pdf/the_golden_gate_bridge.pdf";
public const String DEST = "../../../results/chapter06/the_golden_gate_bridge_nup.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E03_TheGoldenGateBridge_N_up().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//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.AddXObjectAt(pageCopy, 0, orig.GetHeight());
canvas.AddXObjectAt(pageCopy, orig.GetWidth(), orig.GetHeight());
canvas.AddXObjectAt(pageCopy, 0, 0);
canvas.AddXObjectAt(pageCopy, orig.GetWidth(), 0);
pdf.Close();
sourcePdf.Close();
}
}
}
c06e04_88th_oscar_combine
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
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();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Kernel.Utils;
namespace Tutorial.Chapter06 {
public class C06E04_88th_Oscar_Combine {
public const String SRC1 = "../../../resources/pdf/88th_reminder_list.pdf";
public const String SRC2 = "../../../resources/pdf/88th_noms_announcement.pdf";
public const String DEST = "../../../results/chapter06/88th_oscar_combined_documents.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E04_88th_Oscar_Combine().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//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();
}
}
}
c06e05_88th_oscar_combinexofy
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
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();
}
}
C#
using System;
using System.IO;
using iText.Commons.Utils;
using iText.Kernel.Pdf;
using iText.Kernel.Utils;
namespace Tutorial.Chapter06 {
public class C06E05_88th_Oscar_CombineXofY {
public const String SRC1 = "../../../resources/pdf/88th_reminder_list.pdf";
public const String SRC2 = "../../../resources/pdf/88th_noms_announcement.pdf";
public const String DEST = "../../../results/chapter06/88th_oscar_combined_documents_xy_pages.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E05_88th_Oscar_CombineXofY().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//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, JavaUtil.ArraysAsList(1, 5, 7, 1));
//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.Merge(secondSourcePdf, JavaUtil.ArraysAsList(1, 15));
firstSourcePdf.Close();
secondSourcePdf.Close();
pdf.Close();
}
}
}
c06e06_88th_oscar_combine_addtoc
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
import com.itextpdf.kernel.colors.ColorConstants;
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.properties.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.properties.TabAlignment;
import com.itextpdf.layout.properties.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(ColorConstants.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();
}
}
C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace Tutorial.Chapter06 {
public class C06E06_88th_Oscar_Combine_AddTOC {
public const String SRC1 = "../../../resources/pdf/88th_noms_announcement.pdf";
public const String SRC2 = "../../../resources/pdf/oscars_movies_checklist_2016.pdf";
public const String DEST = "../../../results/chapter06/88th_oscar_the_revenant_nominations_TOC.pdf";
public static readonly IDictionary<String, int> TheRevenantNominations = new SortedDictionary<String, int
>();
static C06E06_88th_Oscar_Combine_AddTOC() {
TheRevenantNominations["Performance by an actor in a leading role"] = 4;
TheRevenantNominations["Performance by an actor in a supporting role"] = 4;
TheRevenantNominations["Achievement in cinematography"] = 4;
TheRevenantNominations["Achievement in costume design"] = 5;
TheRevenantNominations["Achievement in directing"] = 5;
TheRevenantNominations["Achievement in film editing"] = 6;
TheRevenantNominations["Achievement in makeup and hairstyling"] = 7;
TheRevenantNominations["Best motion picture of the year"] = 8;
TheRevenantNominations["Achievement in production design"] = 8;
TheRevenantNominations["Achievement in sound editing"] = 9;
TheRevenantNominations["Achievement in sound mixing"] = 9;
TheRevenantNominations["Achievement in visual effects"] = 10;
}
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E06_88th_Oscar_Combine_AddTOC().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
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));
foreach (KeyValuePair<String, int> entry in TheRevenantNominations) {
//Copy page
PdfPage page = firstSourcePdf.GetPage(entry.Value).CopyTo(pdfDoc);
pdfDoc.AddPage(page);
//Overwrite page number
Text text = new Text(String.Format("Page {0}", pdfDoc.GetNumberOfPages() - 1));
text.SetBackgroundColor(ColorConstants.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.Key);
p.Add(new Tab());
p.Add((pdfDoc.GetNumberOfPages() - 1).ToString());
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_1 = secondSourcePdf.GetPage(1).CopyTo(pdfDoc);
pdfDoc.AddPage(page_1);
//Add destination
PdfArray destinationArray_1 = new PdfArray();
destinationArray_1.Add(page_1.GetPdfObject());
destinationArray_1.Add(PdfName.XYZ);
destinationArray_1.Add(new PdfNumber(0));
destinationArray_1.Add(new PdfNumber(page_1.GetMediaBox().GetHeight()));
destinationArray_1.Add(new PdfNumber(1));
pdfDoc.AddNamedDestination("checklist", destinationArray_1);
//Add TOC line with bookmark
Paragraph p_1 = new Paragraph();
p_1.AddTabStops(new TabStop(540, TabAlignment.RIGHT, new DottedLine()));
p_1.Add("Oscars\u00ae 2016 Movie Checklist");
p_1.Add(new Tab());
p_1.Add((pdfDoc.GetNumberOfPages() - 1).ToString());
p_1.SetProperty(Property.ACTION, PdfAction.CreateGoTo("checklist"));
document.Add(p_1);
secondSourcePdf.Close();
// close the document
document.Close();
}
}
}
c06e07_combine_forms
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
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();
}
}
C#
using System;
using System.IO;
using iText.Forms;
using iText.Kernel.Pdf;
namespace Tutorial.Chapter06 {
public class C06E07_Combine_Forms {
public const String DEST = "../../../results/chapter06/combined_forms.pdf";
public const String SRC1 = "../../../resources/pdf/subscribe.pdf";
public const String SRC2 = "../../../resources/pdf/state.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E07_Combine_Forms().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
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();
foreach (PdfDocument sourcePdfDocument in sources) {
sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), destPdfDocument, formCopier);
sourcePdfDocument.Close();
}
destPdfDocument.Close();
}
}
}
c06e08_filloutandmergeforms
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormCreator;
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 = PdfFormCreator.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.getAllFormFields();
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();
}
}
C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.Commons.Utils;
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Source;
using iText.Kernel.Pdf;
namespace Tutorial.Chapter06 {
public class C06E08_FillOutAndMergeForms {
public const String DEST = "../../../results/chapter06/fill_out_and_merge_forms.pdf";
public const String SRC = "../../../resources/pdf/state.pdf";
public const String DATA = "../../../resources/data/united_states.csv";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C06E08_FillOutAndMergeForms().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(dest));
PdfPageFormCopier formCopier = new PdfPageFormCopier();
using (StreamReader sr = File.OpenText(DATA))
{
String line;
bool headerLine = true;
int i = 1;
while ((line = sr.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 = PdfFormCreator.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, ";");
IDictionary<String, PdfFormField> fields = form.GetAllFormFields();
PdfFormField toSet;
fields.TryGetValue("name_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("abbr_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("capital_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("city_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("population_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("surface_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("timezone1_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("timezone2_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("dst_" + i, out toSet);
toSet.SetValue(tokenizer.NextToken());
sourcePdfDocument.Close();
sourcePdfDocument = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
//Copy pages
sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), pdfDocument, formCopier);
sourcePdfDocument.Close();
}
}
pdfDocument.Close();
}
}
}
c06e09_filloutflattenandmergeforms
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package tutorial.chapter06;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormCreator;
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 = PdfFormCreator.getAcroForm(sourcePdfDocument, true);
StringTokenizer tokenizer = new StringTokenizer(line, ";");
Map<String, PdfFormField> fields = form.getAllFormFields();
//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();
}
}
C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Source;
using iText.Kernel.Pdf;
using iText.Commons.Utils;
namespace Tutorial.Chapter06 {
public class C06E09_FillOutFlattenAndMergeForms {
public const String DEST1 = "../../../results/chapter06/fill_out_flatten_forms_merge.pdf";
public const String DEST2 = "../../../results/chapter06/fill_out_flatten_forms_smart_merge.pdf";
public const String SRC = "../../../resources/pdf/state.pdf";
public const String DATA = "../../../resources/data/united_states.csv";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST1);
file.Directory.Create();
file = new FileInfo(DEST2);
file.Directory.Create();
new C06E09_FillOutFlattenAndMergeForms().CreatePdf(DEST1, DEST2);
}
public virtual void CreatePdf(String dest1, String dest2) {
PdfDocument destPdfDocument = new PdfDocument(new PdfWriter(dest1));
//Smart mode
PdfDocument destPdfDocumentSmartMode = new PdfDocument(new PdfWriter(dest2).SetSmartMode(true));
using (StreamReader sr = File.OpenText(DATA))
{
String line;
bool headerLine = true;
int i = 0;
while ((line = sr.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 = PdfFormCreator.GetAcroForm(sourcePdfDocument, true);
StringTokenizer tokenizer = new StringTokenizer(line, ";");
IDictionary<String, PdfFormField> fields = form.GetAllFormFields();
//Fill out fields
PdfFormField toSet;
fields.TryGetValue("name", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("abbr", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("capital", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("city", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("population", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("surface", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("timezone1", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("timezone2", out toSet);
toSet.SetValue(tokenizer.NextToken());
fields.TryGetValue("dst", out toSet);
toSet.SetValue(tokenizer.NextToken());
//Flatten fields
form.FlattenFields();
sourcePdfDocument.Close();
sourcePdfDocument = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
//Copy pages
sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), destPdfDocument, null);
sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), destPdfDocumentSmartMode,
null);
sourcePdfDocument.Close();
}
}
destPdfDocument.Close();
destPdfDocumentSmartMode.Close();
}
}
}
Resources
the_golden_gate_bridge.pdf
88th_reminder_list.pdf
88th_noms_announcement.pdf
oscars_movies_checklist_2016.pdf
subscribe.pdf
state.pdf
united_states.csv
Results
cmp_the_golden_gate_bridge_scale_shrink.pdf
cmp_the_golden_gate_bridge_tiles.pdf
cmp_the_golden_gate_bridge_nup.pdf
cmp_88th_oscar_combined_documents.pdf
cmp_88th_oscar_combined_documents_xy_pages.pdf
cmp_88th_oscar_the_revenant_nominations_TOC.pdf
cmp_fill_out_and_merge_forms.pdf
cmp_fill_out_flatten_forms_merge.pdf
cmp_fill_out_flatten_forms_smart_merge.pdf