iText Building Blocks - Chapter 7: events, viewer preferences, writer properties
c07e01_eventhandlers
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfNumber;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
public class C07E01_EventHandlers {
public static final String DEST = "results/chapter07/jekyll_hyde_page_orientation.pdf";
public static final PdfNumber PORTRAIT = new PdfNumber(0);
public static final PdfNumber LANDSCAPE = new PdfNumber(90);
public static final PdfNumber INVERTEDPORTRAIT = new PdfNumber(180);
public static final PdfNumber SEASCAPE = new PdfNumber(270);
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E01_EventHandlers().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.getCatalog().setPageLayout(PdfName.TwoColumnLeft);
PageRotationEventHandler eventHandler = new PageRotationEventHandler();
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, eventHandler);
Document document = new Document(pdf, PageSize.A8);
document.add(new Paragraph("Dr. Jekyll"));
eventHandler.setRotation(INVERTEDPORTRAIT);
document.add(new AreaBreak());
document.add(new Paragraph("Mr. Hyde"));
eventHandler.setRotation(LANDSCAPE);
document.add(new AreaBreak());
document.add(new Paragraph("Dr. Jekyll"));
eventHandler.setRotation(SEASCAPE);
document.add(new AreaBreak());
document.add(new Paragraph("Mr. Hyde"));
document.close();
}
protected class PageRotationEventHandler implements IEventHandler {
protected PdfNumber rotation = PORTRAIT;
public void setRotation(PdfNumber orientation) {
this.rotation = orientation;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
docEvent.getPage().put(PdfName.Rotate, rotation);
}
}
}
C#
using System;
using System.IO;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace iText.Highlevel.Chapter07 {
public class C07E01_EventHandlers {
public const String DEST = "../../../results/chapter07/jekyll_hyde_page_orientation.pdf";
public static readonly PdfNumber PORTRAIT = new PdfNumber(0);
public static readonly PdfNumber LANDSCAPE = new PdfNumber(90);
public static readonly PdfNumber INVERTEDPORTRAIT = new PdfNumber(180);
public static readonly PdfNumber SEASCAPE = new PdfNumber(270);
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E01_EventHandlers().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.GetCatalog().SetPageLayout(PdfName.TwoColumnLeft);
C07E01_EventHandlers.PageRotationEventHandler eventHandler = new PageRotationEventHandler();
pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, eventHandler);
Document document = new Document(pdf, PageSize.A8);
document.Add(new Paragraph("Dr. Jekyll"));
eventHandler.SetRotation(INVERTEDPORTRAIT);
document.Add(new AreaBreak());
document.Add(new Paragraph("Mr. Hyde"));
eventHandler.SetRotation(LANDSCAPE);
document.Add(new AreaBreak());
document.Add(new Paragraph("Dr. Jekyll"));
eventHandler.SetRotation(SEASCAPE);
document.Add(new AreaBreak());
document.Add(new Paragraph("Mr. Hyde"));
document.Close();
}
protected internal class PageRotationEventHandler : IEventHandler {
protected internal PdfNumber rotation = C07E01_EventHandlers.PORTRAIT;
public virtual void SetRotation(PdfNumber orientation) {
this.rotation = orientation;
}
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
docEvent.GetPage().Put(PdfName.Rotate, this.rotation);
}
internal PageRotationEventHandler() {
}
}
}
}
c07e02_textwatermark
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.DeviceCmyk;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Div;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E02_TextWatermark {
public static final String SRC = "src/main/resources/txt/jekyll_hyde.txt";
public static final String DEST = "results/chapter07/jekyll_hydeV1.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E02_TextWatermark().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.addEventHandler(PdfDocumentEvent.END_PAGE,
new TextWatermark());
// Initialize document
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3));
BufferedReader br = new BufferedReader(new FileReader(SRC));
String line;
Div div = new Div();
while ((line = br.readLine()) != null) {
document.add(new Paragraph(line)
.setFont(bold).setFontSize(12)
.setMarginBottom(0)
.setKeepWithNext(true));
div = new Div()
.setFont(font).setFontSize(11)
.setMarginBottom(18);
while ((line = br.readLine()) != null) {
div.add(
new Paragraph(line)
.setMarginBottom(0)
.setFirstLineIndent(36)
.setMultipliedLeading(1.2f)
);
if (line.isEmpty()) {
document.add(div);
break;
}
}
}
document.add(div);
//Close document
document.close();
}
protected class TextWatermark implements IEventHandler {
Color lime, blue;
PdfFont helvetica;
protected TextWatermark() throws IOException {
helvetica = PdfFontFactory.createFont(StandardFonts.HELVETICA);
lime = new DeviceCmyk(0.208f, 0, 0.584f, 0);
blue = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
int pageNumber = pdf.getPageNumber(page);
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.saveState()
.setFillColor(pageNumber % 2 == 1 ? lime : blue)
.rectangle(pageSize.getLeft(), pageSize.getBottom(),
pageSize.getWidth(), pageSize.getHeight())
.fill().restoreState();
if (pageNumber > 1) {
pdfCanvas.beginText()
.setFontAndSize(helvetica, 10)
.moveText(pageSize.getWidth() / 2 - 120, pageSize.getTop() - 20)
.showText("The Strange Case of Dr. Jekyll and Mr. Hyde")
.moveText(120, -pageSize.getTop() + 40)
.showText(String.valueOf(pageNumber))
.endText();
}
pdfCanvas.release();
}
}
}
C#
using System;
using System.IO;
using iText.IO.Font;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Hyphenation;
using iText.Layout.Properties;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E02_TextWatermark {
public const String SRC = "../../../resources/txt/jekyll_hyde.txt";
public const String DEST = "../../../results/chapter07/jekyll_hydeV1.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E02_TextWatermark().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new TextWatermark());
// Initialize document
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3));
StreamReader sr = File.OpenText(SRC);
String line;
Div div = new Div();
while ((line = sr.ReadLine()) != null) {
document.Add(new Paragraph(line).SetFont(bold).SetFontSize(12).SetMarginBottom(0).SetKeepWithNext(true));
div = new Div().SetFont(font).SetFontSize(11).SetMarginBottom(18);
while ((line = sr.ReadLine()) != null) {
div.Add(new Paragraph(line).SetMarginBottom(0).SetFirstLineIndent(36).SetMultipliedLeading(1.2f));
if (String.IsNullOrEmpty(line)) {
document.Add(div);
break;
}
}
}
document.Add(div);
//Close document
document.Close();
}
protected internal class TextWatermark : IEventHandler {
internal Color lime;
internal Color blue;
internal PdfFont helvetica;
protected internal TextWatermark() {
this.helvetica = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
this.lime = new DeviceCmyk(0.208f, 0, 0.584f, 0);
this.blue = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
}
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdf.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdf);
pdfCanvas.SaveState().SetFillColor(pageNumber % 2 == 1 ? this.lime : this.blue).Rectangle(pageSize.GetLeft
(), pageSize.GetBottom(), pageSize.GetWidth(), pageSize.GetHeight()).Fill().RestoreState();
if (pageNumber > 1) {
pdfCanvas.BeginText().SetFontAndSize(this.helvetica, 10).MoveText(pageSize.GetWidth() / 2 - 120, pageSize.
GetTop() - 20).ShowText("The Strange Case of Dr. Jekyll and Mr. Hyde").MoveText(120, -pageSize.GetTop(
) + 40).ShowText(pageNumber.ToString()).EndText();
}
pdfCanvas.Release();
}
}
}
}
c07e03_pagexofy
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Div;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E03_PageXofY {
public static final String SRC = "src/main/resources/txt/jekyll_hyde.txt";
public static final String DEST = "results/chapter07/jekyll_hydeV2.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E03_PageXofY().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.addEventHandler(PdfDocumentEvent.START_PAGE,
new Header("The Strange Case of Dr. Jekyll and Mr. Hyde"));
PageXofY event = new PageXofY(pdf);
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, event);
// Initialize document
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3));
BufferedReader br = new BufferedReader(new FileReader(SRC));
String line;
Div div = new Div();
while ((line = br.readLine()) != null) {
document.add(new Paragraph(line)
.setFont(bold).setFontSize(12)
.setMarginBottom(0)
.setKeepWithNext(true));
div = new Div()
.setFont(font).setFontSize(11)
.setMarginBottom(18);
while ((line = br.readLine()) != null) {
div.add(
new Paragraph(line)
.setMarginBottom(0)
.setFirstLineIndent(36)
.setMultipliedLeading(1.2f)
);
if (line.isEmpty()) {
document.add(div);
break;
}
}
}
document.add(div);
event.writeTotal(pdf);
//Close document
document.close();
}
protected class Header implements IEventHandler {
String header;
public Header(String header) {
this.header = header;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
if (pdf.getPageNumber(page) == 1) return;
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(
page.getLastContentStream(), page.getResources(), pdf);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
canvas.showTextAligned(header,
pageSize.getWidth() / 2,
pageSize.getTop() - 30, TextAlignment.CENTER);
}
}
protected class PageXofY implements IEventHandler {
protected PdfFormXObject placeholder;
protected float side = 20;
protected float x = 300;
protected float y = 25;
protected float space = 4.5f;
protected float descent = 3;
public PageXofY(PdfDocument pdf) {
placeholder = new PdfFormXObject(new Rectangle(0, 0, side, side));
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
int pageNumber = pdf.getPageNumber(page);
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(
page.getLastContentStream(), page.getResources(), pdf);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
Paragraph p = new Paragraph()
.add("Page ").add(String.valueOf(pageNumber)).add(" of");
canvas.showTextAligned(p, x, y, TextAlignment.RIGHT);
pdfCanvas.addXObjectAt(placeholder, x + space, y - descent);
pdfCanvas.release();
}
public void writeTotal(PdfDocument pdf) {
Canvas canvas = new Canvas(placeholder, pdf);
canvas.showTextAligned(String.valueOf(pdf.getNumberOfPages()),
0, descent, TextAlignment.LEFT);
}
}
}
C#
using System;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Xobject;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Hyphenation;
using iText.Layout.Properties;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E03_PageXofY {
public const String SRC = "../../../resources/txt/jekyll_hyde.txt";
public const String DEST = "../../../results/chapter07/jekyll_hydeV2.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E03_PageXofY().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, new C07E03_PageXofY.Header("The Strange Case of Dr. Jekyll and Mr. Hyde"));
C07E03_PageXofY.PageXofY @event = new C07E03_PageXofY.PageXofY(pdf);
pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, @event);
// Initialize document
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3));
StreamReader sr = File.OpenText(SRC);
String line;
Div div = new Div();
while ((line = sr.ReadLine()) != null) {
document.Add(new Paragraph(line).SetFont(bold).SetFontSize(12).SetMarginBottom(0).SetKeepWithNext(true));
div = new Div().SetFont(font).SetFontSize(11).SetMarginBottom(18);
while ((line = sr.ReadLine()) != null) {
div.Add(new Paragraph(line).SetMarginBottom(0).SetFirstLineIndent(36).SetMultipliedLeading(1.2f));
if (String.IsNullOrEmpty(line)) {
document.Add(div);
break;
}
}
}
document.Add(div);
@event.WriteTotal(pdf);
//Close document
document.Close();
}
protected internal class Header : IEventHandler {
internal String header;
public Header(String header) {
this.header = header;
}
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
if (pdf.GetPageNumber(page) == 1) {
return;
}
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.GetLastContentStream(), page.GetResources(), pdf);
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, pageSize);
canvas.ShowTextAligned(this.header, pageSize.GetWidth() / 2, pageSize.GetTop() - 30, TextAlignment.CENTER);
}
}
protected internal class PageXofY : IEventHandler {
protected internal PdfFormXObject placeholder;
protected internal float side = 20;
protected internal float x = 300;
protected internal float y = 25;
protected internal float space = 4.5f;
protected internal float descent = 3;
public PageXofY(PdfDocument pdf) {
this.placeholder = new PdfFormXObject(new Rectangle(0, 0, this.side, this.side));
}
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdf.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.GetLastContentStream(), page.GetResources(), pdf);
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, pageSize);
Paragraph p = new Paragraph().Add("Page ").Add(pageNumber.ToString()).Add(" of");
canvas.ShowTextAligned(p, this.x, this.y, TextAlignment.RIGHT);
pdfCanvas.AddXObjectAt(this.placeholder, this.x + this.space, this.y - this.descent);
pdfCanvas.Release();
}
public virtual void WriteTotal(PdfDocument pdf) {
iText.Layout.Canvas canvas = new iText.Layout.Canvas(this.placeholder, pdf);
canvas.ShowTextAligned(pdf.GetNumberOfPages().ToString(), 0, this.descent, TextAlignment.LEFT);
}
}
}
}
c07e04_imagewatermark
CODE
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.kernel.pdf.extgstate.PdfExtGState;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.layout.LayoutContext;
import com.itextpdf.layout.layout.LayoutResult;
import com.itextpdf.layout.properties.AreaBreakType;
import com.itextpdf.layout.properties.TabAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.renderer.ParagraphRenderer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E04_ImageWatermark {
public static final String SRC = "src/main/resources/txt/jekyll_hyde.txt";
public static final String IMG = "src/main/resources/img/3132614.jpg";
public static final String DEST = "results/chapter07/jekyll_hydeV3.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E04_ImageWatermark().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
Image img = new Image(ImageDataFactory.create(IMG));
IEventHandler handler = new TransparentImage(img);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, handler);
// Initialize document
Document document = new Document(pdf);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3));
BufferedReader br = new BufferedReader(new FileReader(SRC));
String name, line;
Paragraph p;
boolean title = true;
int counter = 0;
List<SimpleEntry<String,SimpleEntry<String, Integer>>> toc = new ArrayList<>();
while ((line = br.readLine()) != null) {
p = new Paragraph(line);
p.setKeepTogether(true);
if (title) {
name = String.format("title%02d", counter++);
SimpleEntry<String, Integer> titlePage
= new SimpleEntry(line, pdf.getNumberOfPages());
p.setFont(bold).setFontSize(12)
.setKeepWithNext(true)
.setDestination(name)
.setNextRenderer(new UpdatePageRenderer(p, titlePage));
title = false;
document.add(p);
toc.add(new SimpleEntry(name, titlePage));
}
else {
p.setFirstLineIndent(36);
if (line.isEmpty()) {
p.setMarginBottom(12);
title = true;
}
else {
p.setMarginBottom(0);
}
document.add(p);
}
}
pdf.removeEventHandler(PdfDocumentEvent.START_PAGE, handler);
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().setFont(bold)
.add("Table of Contents").setDestination("toc");
document.add(p);
toc.remove(0);
List<TabStop> tabstops = new ArrayList();
tabstops.add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
for (SimpleEntry<String, SimpleEntry<String, Integer>> entry : toc) {
SimpleEntry<String, Integer> text = entry.getValue();
p = new Paragraph()
.addTabStops(tabstops)
.add(text.getKey())
.add(new Tab())
.add(String.valueOf(text.getValue()))
.setAction(PdfAction.createGoTo(entry.getKey()));
document.add(p);
}
//Close document
document.close();
}
protected class UpdatePageRenderer extends ParagraphRenderer {
protected SimpleEntry<String, Integer> entry;
public UpdatePageRenderer(Paragraph modelElement, SimpleEntry<String, Integer> entry) {
super(modelElement);
this.entry = entry;
}
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutResult result = super.layout(layoutContext);
entry.setValue(layoutContext.getArea().getPageNumber());
return result;
}
}
protected class TransparentImage implements IEventHandler {
protected PdfExtGState gState;
protected Image img;
public TransparentImage(Image img) {
this.img = img;
gState = new PdfExtGState().setFillOpacity(0.2f);
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(
page.getLastContentStream(), page.getResources(), pdf);
pdfCanvas.saveState().setExtGState(gState);
Canvas canvas = new Canvas(pdfCanvas, page.getPageSize());
canvas.add(img
.scaleAbsolute(pageSize.getWidth(), pageSize.getHeight()));
pdfCanvas.restoreState();
pdfCanvas.release();
}
}
}
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.IO.Image;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Kernel.Pdf.Extgstate;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Hyphenation;
using iText.Layout.Layout;
using iText.Layout.Properties;
using iText.Layout.Renderer;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E04_ImageWatermark {
public const String SRC = "../../../resources/txt/jekyll_hyde.txt";
public const String IMG = "../../../resources/img/3132614.jpg";
public const String DEST = "../../../results/chapter07/jekyll_hydeV3.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E04_ImageWatermark().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
iText.Layout.Element.Image img = new Image(ImageDataFactory.Create(IMG));
IEventHandler handler = new TransparentImage( img);
pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
// Initialize document
Document document = new Document(pdf);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3));
StreamReader sr = File.OpenText(SRC);
String name;
String line;
Paragraph p;
bool title = true;
int counter = 0;
IList<Util.Pair<String, Util.Pair<String, int>>> toc = new List<Util.Pair
<String, Util.Pair<String, int>>>();
while ((line = sr.ReadLine()) != null) {
p = new Paragraph(line);
p.SetKeepTogether(true);
if (title) {
name = String.Format("title{0:00}", counter++);
Util.Pair<String, int> titlePage = new Util.Pair<string,int>(line, pdf.GetNumberOfPages());
p.SetFont(bold).
SetFontSize(12)
.SetKeepWithNext(true)
.SetDestination(name)
.SetNextRenderer(new UpdatePageRenderer(p, titlePage));
title = false;
document.Add(p);
toc.Add(new Util.Pair<string,Util.Pair<string,int>>(name, titlePage));
}
else {
p.SetFirstLineIndent(36);
if (String.IsNullOrEmpty(line)) {
p.SetMarginBottom(12);
title = true;
}
else {
p.SetMarginBottom(0);
}
document.Add(p);
}
}
pdf.RemoveEventHandler(PdfDocumentEvent.START_PAGE, handler);
document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().SetFont(bold).Add("Table of Contents").SetDestination("toc");
document.Add(p);
toc.RemoveAt(0);
IList<TabStop> tabstops = new List<TabStop>();
tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
foreach (Util.Pair<String, Util.Pair<String, int>> entry in toc) {
Util.Pair<String, int> text = entry.Value;
p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
(PdfAction.CreateGoTo(entry.Key));
document.Add(p);
}
//Close document
document.Close();
}
protected internal class UpdatePageRenderer : ParagraphRenderer {
protected internal Util.Pair<String, int> entry;
public UpdatePageRenderer(Paragraph modelElement, Util.Pair
<String, int> entry)
: base(modelElement) {
this.entry = entry;
}
public override LayoutResult Layout(LayoutContext layoutContext) {
LayoutResult result = base.Layout(layoutContext);
this.entry.Value = layoutContext.GetArea().GetPageNumber();
return result;
}
}
protected internal class TransparentImage : IEventHandler {
protected internal PdfExtGState gState;
protected internal iText.Layout.Element.Image img;
public TransparentImage(iText.Layout.Element.Image img) {
this.img = img;
this.gState = new PdfExtGState().SetFillOpacity(0.2f);
}
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.GetLastContentStream(), page.GetResources(), pdf);
pdfCanvas.SaveState().SetExtGState(this.gState);
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, page.GetPageSize());
canvas.Add(this.img.ScaleAbsolute(pageSize.GetWidth(), pageSize.GetHeight()));
pdfCanvas.RestoreState();
pdfCanvas.Release();
}
}
}
}
c07e05_addremovepages
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
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.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
public class C07E05_AddRemovePages {
public static final String SRC = "src/main/resources/pdfs/jekyll_hyde_bookmarked.pdf";
public static final String DEST = "results/chapter07/jekyll_hyde_updated.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E05_AddRemovePages().manipulatePdf(SRC, DEST);
}
public void manipulatePdf(String src, String dest) throws IOException {
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(reader, writer);
pdf.addEventHandler(PdfDocumentEvent.INSERT_PAGE, new AddPageHandler());
pdf.addEventHandler(PdfDocumentEvent.REMOVE_PAGE, new RemovePageHandler());
pdf.addNewPage(1, PageSize.A4);
int total = pdf.getNumberOfPages();
for (int i = 9; i <= total; i++) {
pdf.removePage(9);
if (i == 12)
pdf.removeAllHandlers();
}
pdf.close();
}
protected class AddPageHandler implements IEventHandler {
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Canvas canvas = new Canvas(pdfCanvas, page.getPageSize());
canvas.add(new Paragraph().add(docEvent.getType()));
}
}
protected class RemovePageHandler implements IEventHandler {
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
System.out.println(docEvent.getType());
}
}
}
C#
using System;
using System.IO;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout.Element;
namespace iText.Highlevel.Chapter07 {
public class C07E05_AddRemovePages {
public const String SRC = "../../../resources/pdfs/jekyll_hyde_bookmarked.pdf";
public const String DEST = "../../../results/chapter07/jekyll_hyde_updated.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E05_AddRemovePages().ManipulatePdf(SRC, DEST);
}
public virtual void ManipulatePdf(String src, String dest) {
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(reader, writer);
pdf.AddEventHandler(PdfDocumentEvent.INSERT_PAGE, new AddPageHandler());
pdf.AddEventHandler(PdfDocumentEvent.REMOVE_PAGE, new RemovePageHandler());
pdf.AddNewPage(1, PageSize.A4);
int total = pdf.GetNumberOfPages();
for (int i = 9; i <= total; i++) {
pdf.RemovePage(9);
if (i == 12) {
pdf.RemoveAllHandlers();
}
}
pdf.Close();
}
protected internal class AddPageHandler : IEventHandler {
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, page.GetPageSize());
canvas.Add(new Paragraph().Add(docEvent.GetEventType()));
}
internal AddPageHandler() {
}
}
protected internal class RemovePageHandler : IEventHandler {
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
System.Console.Out.WriteLine(docEvent.GetEventType());
}
internal RemovePageHandler() {
}
}
}
}
c07e06_pagelabels
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PageLabelNumberingStyle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.properties.AreaBreakType;
import com.itextpdf.layout.properties.TabAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E06_PageLabels {
public static final String SRC = "src/main/resources/txt/jekyll_hyde.txt";
public static final String DEST = "results/chapter07/pagelabels.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E06_PageLabels().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfPage page = pdf.addNewPage();
page.setPageLabel(PageLabelNumberingStyle.LOWERCASE_ROMAN_NUMERALS, null);
Document document = new Document(pdf);
document.add(new Paragraph().add("Page left blank intentionally"));
document.add(new AreaBreak());
document.add(new Paragraph().add("Page left blank intentionally"));
document.add(new AreaBreak());
document.add(new Paragraph().add("Page left blank intentionally"));
document.add(new AreaBreak());
page = pdf.getLastPage();
page.setPageLabel(PageLabelNumberingStyle.DECIMAL_ARABIC_NUMERALS, null, 1);
PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.setFont(font)
.setFontSize(11);
BufferedReader br = new BufferedReader(new FileReader(SRC));
String name, line;
Paragraph p;
boolean title = true;
int counter = 0;
List<AbstractMap.SimpleEntry<String,AbstractMap.SimpleEntry<String, Integer>>> toc = new ArrayList<>();
while ((line = br.readLine()) != null) {
p = new Paragraph(line);
p.setKeepTogether(true);
if (title) {
name = String.format("title%02d", counter++);
p.setFont(bold).setFontSize(12)
.setKeepWithNext(true)
.setDestination(name);
title = false;
document.add(p);
toc.add(new AbstractMap.SimpleEntry(name, new AbstractMap.SimpleEntry(line, pdf.getNumberOfPages())));
}
else {
p.setFirstLineIndent(36);
if (line.isEmpty()) {
p.setMarginBottom(12);
title = true;
}
else {
p.setMarginBottom(0);
}
document.add(p);
}
}
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().setFont(bold)
.add("Table of Contents").setDestination("toc");
document.add(p);
page = pdf.getLastPage();
page.setPageLabel(null, "TOC", 1);
toc.remove(0);
List<TabStop> tabstops = new ArrayList();
tabstops.add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
for (AbstractMap.SimpleEntry<String, AbstractMap.SimpleEntry<String, Integer>> entry : toc) {
AbstractMap.SimpleEntry<String, Integer> text = entry.getValue();
p = new Paragraph()
.addTabStops(tabstops)
.add(text.getKey())
.add(new Tab())
.add(String.valueOf(text.getValue()))
.setAction(PdfAction.createGoTo(entry.getKey()));
document.add(p);
}
document.close();
}
}
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Font;
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.Hyphenation;
using iText.Layout.Properties;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E06_PageLabels {
public const String SRC = "../../../resources/txt/jekyll_hyde.txt";
public const String DEST = "../../../results/chapter07/pagelabels.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E06_PageLabels().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfPage page = pdf.AddNewPage();
page.SetPageLabel(PageLabelNumberingStyle.LOWERCASE_ROMAN_NUMERALS, null);
Document document = new Document(pdf);
document.Add(new Paragraph().Add("Page left blank intentionally"));
document.Add(new AreaBreak());
document.Add(new Paragraph().Add("Page left blank intentionally"));
document.Add(new AreaBreak());
document.Add(new Paragraph().Add("Page left blank intentionally"));
document.Add(new AreaBreak());
page = pdf.GetLastPage();
page.SetPageLabel(PageLabelNumberingStyle.DECIMAL_ARABIC_NUMERALS, null, 1);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.SetFont(font).SetFontSize(11);
StreamReader sr = File.OpenText(SRC);
String name;
String line;
Paragraph p;
bool title = true;
int counter = 0;
IList<Util.Pair<String, Util.Pair<String, int>>> toc = new List<Util.Pair
<String, Util.Pair<String, int>>>();
while ((line = sr.ReadLine()) != null) {
p = new Paragraph(line);
p.SetKeepTogether(true);
if (title) {
name = String.Format("title{0:00}", counter++);
p.SetFont(bold).SetFontSize(12).SetKeepWithNext(true).SetDestination(name);
title = false;
document.Add(p);
toc.Add(new Util.Pair<string,Util.Pair<string, int>>(name, new Util.Pair<String,int>(line, pdf.GetNumberOfPages())));
}
else {
p.SetFirstLineIndent(36);
if (String.IsNullOrEmpty(line)) {
p.SetMarginBottom(12);
title = true;
}
else {
p.SetMarginBottom(0);
}
document.Add(p);
}
}
document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().SetFont(bold).Add("Table of Contents").SetDestination("toc");
document.Add(p);
page = pdf.GetLastPage();
page.SetPageLabel(null, "TOC", 1);
toc.RemoveAt(0);
IList<TabStop> tabstops = new List<TabStop>();
tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
foreach (Util.Pair<String, Util.Pair<String, int>> entry in toc) {
Util.Pair<String, int> text = entry.Value;
p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
(PdfAction.CreateGoTo(entry.Key));
document.Add(p);
}
document.Close();
}
}
}
c07e07_pagelayoutpagemode
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PageLabelNumberingStyle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.properties.AreaBreakType;
import com.itextpdf.layout.properties.TabAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E07_PageLayoutPageMode {
public static final String SRC = "src/main/resources/txt/jekyll_hyde.txt";
public static final String DEST = "results/chapter07/page_mode_page_layout.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E07_PageLayoutPageMode().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.getCatalog().setPageLayout(PdfName.TwoColumnRight);
pdf.getCatalog().setPageMode(PdfName.UseThumbs);
PdfPage page = pdf.addNewPage();
page.setPageLabel(PageLabelNumberingStyle.LOWERCASE_ROMAN_NUMERALS, null);
Document document = new Document(pdf);
document.add(new Paragraph().add("Page left blank intentionally"));
document.add(new AreaBreak());
document.add(new Paragraph().add("Page left blank intentionally"));
document.add(new AreaBreak());
document.add(new Paragraph().add("Page left blank intentionally"));
document.add(new AreaBreak());
page = pdf.getLastPage();
page.setPageLabel(PageLabelNumberingStyle.DECIMAL_ARABIC_NUMERALS, null, 1);
PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.setFont(font)
.setFontSize(11);
BufferedReader br = new BufferedReader(new FileReader(SRC));
String name, line;
Paragraph p;
boolean title = true;
int counter = 0;
List<AbstractMap.SimpleEntry<String,AbstractMap.SimpleEntry<String, Integer>>> toc = new ArrayList<>();
while ((line = br.readLine()) != null) {
p = new Paragraph(line);
p.setKeepTogether(true);
if (title) {
name = String.format("title%02d", counter++);
p.setFont(bold).setFontSize(12)
.setKeepWithNext(true)
.setDestination(name);
title = false;
document.add(p);
toc.add(new AbstractMap.SimpleEntry(name, new AbstractMap.SimpleEntry(line, pdf.getNumberOfPages())));
}
else {
p.setFirstLineIndent(36);
if (line.isEmpty()) {
p.setMarginBottom(12);
title = true;
}
else {
p.setMarginBottom(0);
}
document.add(p);
}
}
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().setFont(bold)
.add("Table of Contents").setDestination("toc");
document.add(p);
page = pdf.getLastPage();
page.setPageLabel(null, "TOC", 1);
toc.remove(0);
List<TabStop> tabstops = new ArrayList();
tabstops.add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
for (AbstractMap.SimpleEntry<String, AbstractMap.SimpleEntry<String, Integer>> entry : toc) {
AbstractMap.SimpleEntry<String, Integer> text = entry.getValue();
p = new Paragraph()
.addTabStops(tabstops)
.add(text.getKey())
.add(new Tab())
.add(String.valueOf(text.getValue()))
.setAction(PdfAction.createGoTo(entry.getKey()));
document.add(p);
}
document.close();
}
}
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Font;
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.Hyphenation;
using iText.Layout.Properties;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E07_PageLayoutPageMode {
public const String SRC = "../../../resources/txt/jekyll_hyde.txt";
public const String DEST = "../../../results/chapter07/page_mode_page_layout.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E07_PageLayoutPageMode().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.GetCatalog().SetPageLayout(PdfName.TwoColumnRight);
pdf.GetCatalog().SetPageMode(PdfName.UseThumbs);
PdfPage page = pdf.AddNewPage();
page.SetPageLabel(PageLabelNumberingStyle.LOWERCASE_ROMAN_NUMERALS, null);
Document document = new Document(pdf);
document.Add(new Paragraph().Add("Page left blank intentionally"));
document.Add(new AreaBreak());
document.Add(new Paragraph().Add("Page left blank intentionally"));
document.Add(new AreaBreak());
document.Add(new Paragraph().Add("Page left blank intentionally"));
document.Add(new AreaBreak());
page = pdf.GetLastPage();
page.SetPageLabel(PageLabelNumberingStyle.DECIMAL_ARABIC_NUMERALS, null, 1);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.SetFont(font).SetFontSize(11);
StreamReader sr = File.OpenText(SRC);
String name;
String line;
Paragraph p;
bool title = true;
int counter = 0;
IList<Util.Pair<String, Util.Pair<String, int>>> toc = new List<Util.Pair
<String, Util.Pair<String, int>>>();
while ((line = sr.ReadLine()) != null) {
p = new Paragraph(line);
p.SetKeepTogether(true);
if (title) {
name = String.Format("title{0:00}", counter++);
p.SetFont(bold).SetFontSize(12).SetKeepWithNext(true).SetDestination(name);
title = false;
document.Add(p);
toc.Add(new Util.Pair<string,Util.Pair<string,int>>(name, new Util.Pair<string,int>(line, pdf.GetNumberOfPages())));
}
else {
p.SetFirstLineIndent(36);
if (String.IsNullOrEmpty(line)) {
p.SetMarginBottom(12);
title = true;
}
else {
p.SetMarginBottom(0);
}
document.Add(p);
}
}
document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().SetFont(bold).Add("Table of Contents").SetDestination("toc");
document.Add(p);
page = pdf.GetLastPage();
page.SetPageLabel(null, "TOC", 1);
toc.RemoveAt(0);
IList<TabStop> tabstops = new List<TabStop>();
tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
foreach (Util.Pair<String, Util.Pair<String, int>> entry in toc) {
Util.Pair<String, int> text = entry.Value;
p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
(PdfAction.CreateGoTo(entry.Key));
document.Add(p);
}
document.Close();
}
}
}
c07e08_fullscreen
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfViewerPreferences;
import com.itextpdf.kernel.pdf.PdfViewerPreferences.PdfViewerPreferencesConstants;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E08_FullScreen {
public static final String DEST = "results/chapter07/fullscreen.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E08_FullScreen().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.getCatalog().setPageMode(PdfName.FullScreen);
PdfViewerPreferences preferences = new PdfViewerPreferences();
preferences.setNonFullScreenPageMode(PdfViewerPreferencesConstants.USE_THUMBS);
pdf.getCatalog().setViewerPreferences(preferences);
Document document = new Document(pdf, PageSize.A8);
document.add(new Paragraph("Mr. Jekyl"));
document.add(new AreaBreak());
document.add(new Paragraph("Mr. Hyde"));
document.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E08_FullScreen {
public const String DEST = "../../../results/chapter07/fullscreen.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E08_FullScreen().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.GetCatalog().SetPageMode(PdfName.FullScreen);
PdfViewerPreferences preferences = new PdfViewerPreferences();
preferences.SetNonFullScreenPageMode(PdfViewerPreferences.PdfViewerPreferencesConstants.USE_THUMBS);
pdf.GetCatalog().SetViewerPreferences(preferences);
Document document = new Document(pdf, PageSize.A8);
document.Add(new Paragraph("Mr. Jekyl"));
document.Add(new AreaBreak());
document.Add(new Paragraph("Mr. Hyde"));
document.Close();
}
}
}
c07e09_viewerpreferences
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfDocumentInfo;
import com.itextpdf.kernel.pdf.PdfViewerPreferences;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E09_ViewerPreferences {
public static final String DEST = "results/chapter07/viewerpreferences.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E09_ViewerPreferences().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfViewerPreferences preferences = new PdfViewerPreferences();
preferences.setFitWindow(true);
preferences.setHideMenubar(true);
preferences.setHideToolbar(true);
preferences.setHideWindowUI(true);
preferences.setCenterWindow(true);
preferences.setDisplayDocTitle(true);
pdf.getCatalog().setViewerPreferences(preferences);
PdfDocumentInfo info = pdf.getDocumentInfo();
info.setTitle("A Strange Case");
Document document = new Document(pdf, PageSize.A4.rotate());
document.add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
document.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E09_ViewerPreferences {
public const String DEST = "../../../results/chapter07/viewerpreferences.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E09_ViewerPreferences().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfViewerPreferences preferences = new PdfViewerPreferences();
preferences.SetFitWindow(true);
preferences.SetHideMenubar(true);
preferences.SetHideToolbar(true);
preferences.SetHideWindowUI(true);
preferences.SetCenterWindow(true);
preferences.SetDisplayDocTitle(true);
pdf.GetCatalog().SetViewerPreferences(preferences);
PdfDocumentInfo info = pdf.GetDocumentInfo();
info.SetTitle("A Strange Case");
Document document = new Document(pdf, PageSize.A4.Rotate());
document.Add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
document.Close();
}
}
}
c07e10_printerpreferences
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfDocumentInfo;
import com.itextpdf.kernel.pdf.PdfViewerPreferences;
import com.itextpdf.kernel.pdf.PdfViewerPreferences.PdfViewerPreferencesConstants;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E10_PrinterPreferences {
public static final String DEST = "results/chapter07/printerpreferences.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E10_PrinterPreferences().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfViewerPreferences preferences = new PdfViewerPreferences();
preferences.setPrintScaling(PdfViewerPreferencesConstants.NONE);
preferences.setNumCopies(5);
pdf.getCatalog().setViewerPreferences(preferences);
PdfDocumentInfo info = pdf.getDocumentInfo();
info.setTitle("A Strange Case");
Document document = new Document(pdf, PageSize.A4.rotate());
document.add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
document.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E10_PrinterPreferences {
public const String DEST = "../../../results/chapter07/printerpreferences.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E10_PrinterPreferences().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfViewerPreferences preferences = new PdfViewerPreferences();
preferences.SetPrintScaling(PdfViewerPreferences.PdfViewerPreferencesConstants.NONE);
preferences.SetNumCopies(5);
pdf.GetCatalog().SetViewerPreferences(preferences);
PdfDocumentInfo info = pdf.GetDocumentInfo();
info.SetTitle("A Strange Case");
Document document = new Document(pdf, PageSize.A4.Rotate());
document.Add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
document.Close();
}
}
}
c07e11_actions
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.kernel.pdf.navigation.PdfDestination;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.properties.AreaBreakType;
import com.itextpdf.layout.properties.TabAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E11_Actions {
public static final String SRC = "src/main/resources/txt/jekyll_hyde.txt";
public static final String DEST = "results/chapter07/jekyll_hyde_document_actions.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E11_Actions().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.getCatalog().setOpenAction(
PdfDestination.makeDestination(new PdfString("toc")));
pdf.getCatalog().setAdditionalAction(
PdfName.WC, PdfAction.createJavaScript("app.alert('Thank you for reading');"));
pdf.addNewPage().setAdditionalAction(
PdfName.O, PdfAction.createJavaScript("app.alert('This is where it starts!');"));
// Initialize document
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.setFont(font)
.setFontSize(11);
BufferedReader br = new BufferedReader(new FileReader(SRC));
String name, line;
Paragraph p;
boolean title = true;
int counter = 0;
List<SimpleEntry<String,SimpleEntry<String, Integer>>> toc = new ArrayList<>();
while ((line = br.readLine()) != null) {
p = new Paragraph(line);
p.setKeepTogether(true);
if (title) {
name = String.format("title%02d", counter++);
p.setFont(bold).setFontSize(12)
.setKeepWithNext(true)
.setDestination(name);
title = false;
document.add(p);
toc.add(new SimpleEntry(name, new SimpleEntry(line, pdf.getNumberOfPages())));
}
else {
p.setFirstLineIndent(36);
if (line.isEmpty()) {
p.setMarginBottom(12);
title = true;
}
else {
p.setMarginBottom(0);
}
document.add(p);
}
}
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().setFont(bold)
.add("Table of Contents").setDestination("toc");
document.add(p);
toc.remove(0);
List<TabStop> tabstops = new ArrayList();
tabstops.add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
for (SimpleEntry<String, SimpleEntry<String, Integer>> entry : toc) {
SimpleEntry<String, Integer> text = entry.getValue();
p = new Paragraph()
.addTabStops(tabstops)
.add(text.getKey())
.add(new Tab())
.add(String.valueOf(text.getValue()))
.setAction(PdfAction.createGoTo(entry.getKey()));
document.add(p);
}
PdfPage page = pdf.getLastPage();
page.setAdditionalAction(PdfName.C, PdfAction.createJavaScript("app.alert('Goodbye last page!');"));
//Close document
document.close();
}
}
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Kernel.Pdf.Navigation;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Hyphenation;
using iText.Layout.Properties;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E11_Actions {
public const String SRC = "../../../resources/txt/jekyll_hyde.txt";
public const String DEST = "../../../results/chapter07/jekyll_hyde_document_actions.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E11_Actions().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.GetCatalog().SetOpenAction(PdfDestination.MakeDestination(new PdfString("toc")));
pdf.GetCatalog().SetAdditionalAction(PdfName.WC, PdfAction.CreateJavaScript("app.alert('Thank you for reading');"
));
pdf.AddNewPage().SetAdditionalAction(PdfName.O, PdfAction.CreateJavaScript("app.alert('This is where it starts!');"
));
// Initialize document
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3))
.SetFont(font).SetFontSize(11);
StreamReader sr = File.OpenText(SRC);
String name;
String line;
Paragraph p;
bool title = true;
int counter = 0;
IList<Util.Pair<String, Util.Pair<String, int>>> toc = new List<Util.Pair
<String, Util.Pair<String, int>>>();
while ((line = sr.ReadLine()) != null) {
p = new Paragraph(line);
p.SetKeepTogether(true);
if (title) {
name = String.Format("title{0:00}", counter++);
p.SetFont(bold).SetFontSize(12).SetKeepWithNext(true).SetDestination(name);
title = false;
document.Add(p);
toc.Add(new Util.Pair<string,Util.Pair<string,int>>(name, new Util.Pair<string,int>(line, pdf.GetNumberOfPages())));
}
else {
p.SetFirstLineIndent(36);
if (String.IsNullOrEmpty(line)) {
p.SetMarginBottom(12);
title = true;
}
else {
p.SetMarginBottom(0);
}
document.Add(p);
}
}
document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().SetFont(bold).Add("Table of Contents").SetDestination("toc");
document.Add(p);
toc.RemoveAt(0);
IList<TabStop> tabstops = new List<TabStop>();
tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
foreach (Util.Pair<String, Util.Pair<String, int>> entry in toc) {
Util.Pair<String, int> text = entry.Value;
p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
(PdfAction.CreateGoTo(entry.Key));
document.Add(p);
}
PdfPage page = pdf.GetLastPage();
page.SetAdditionalAction(PdfName.C, PdfAction.CreateJavaScript("app.alert('Goodbye last page!');"));
//Close document
document.Close();
}
}
}
c07e12_metadata
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfDocumentInfo;
import com.itextpdf.kernel.pdf.PdfVersion;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.WriterProperties;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E12_Metadata {
public static final String DEST = "results/chapter07/metadata.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E12_Metadata().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(
new PdfWriter(dest,
new WriterProperties()
.addXmpMetadata()
.setPdfVersion(PdfVersion.PDF_1_6)));
PdfDocumentInfo info = pdf.getDocumentInfo();
info.setTitle("The Strange Case of Dr. Jekyll and Mr. Hyde");
info.setAuthor("Robert Louis Stevenson");
info.setSubject("A novel");
info.setKeywords("Dr. Jekyll, Mr. Hyde");
info.setCreator("A simple tutorial example");
Document document = new Document(pdf);
document.add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
document.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E12_Metadata {
public const String DEST = "../../../results/chapter07/metadata.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E12_Metadata().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest, new WriterProperties().AddXmpMetadata().SetPdfVersion
(PdfVersion.PDF_1_6)));
PdfDocumentInfo info = pdf.GetDocumentInfo();
info.SetTitle("The Strange Case of Dr. Jekyll and Mr. Hyde");
info.SetAuthor("Robert Louis Stevenson");
info.SetSubject("A novel");
info.SetKeywords("Dr. Jekyll, Mr. Hyde");
info.SetCreator("A simple tutorial example");
Document document = new Document(pdf);
document.Add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
document.Close();
}
}
}
c07e13_compressed
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.WriterProperties;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.kernel.pdf.extgstate.PdfExtGState;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.hyphenation.HyphenationConfig;
import com.itextpdf.layout.properties.AreaBreakType;
import com.itextpdf.layout.properties.TabAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E13_Compressed {
public static final String SRC = "src/main/resources/txt/jekyll_hyde.txt";
public static final String IMG = "src/main/resources/img/3132614.jpg";
public static final String DEST = "results/chapter07/jekyll_hyde_compressed.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E13_Compressed().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest,
new WriterProperties().setFullCompressionMode(true)));
Image img = new Image(ImageDataFactory.create(IMG));
IEventHandler handler = new TransparentImage(img);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, handler);
// Initialize document
Document document = new Document(pdf);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
document.setTextAlignment(TextAlignment.JUSTIFIED)
.setHyphenation(new HyphenationConfig("en", "uk", 3, 3));
BufferedReader br = new BufferedReader(new FileReader(SRC));
String name, line;
Paragraph p;
boolean title = true;
int counter = 0;
List<SimpleEntry<String,SimpleEntry<String, Integer>>> toc = new ArrayList<>();
while ((line = br.readLine()) != null) {
p = new Paragraph(line);
p.setKeepTogether(true);
if (title) {
name = String.format("title%02d", counter++);
p.setFont(bold).setFontSize(12)
.setKeepWithNext(true)
.setDestination(name);
title = false;
document.add(p);
toc.add(new SimpleEntry(name, new SimpleEntry(line, pdf.getNumberOfPages())));
}
else {
p.setFirstLineIndent(36);
if (line.isEmpty()) {
p.setMarginBottom(12);
title = true;
}
else {
p.setMarginBottom(0);
}
document.add(p);
}
}
pdf.removeEventHandler(PdfDocumentEvent.START_PAGE, handler);
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().setFont(bold)
.add("Table of Contents").setDestination("toc");
document.add(p);
toc.remove(0);
List<TabStop> tabstops = new ArrayList();
tabstops.add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
for (SimpleEntry<String, SimpleEntry<String, Integer>> entry : toc) {
SimpleEntry<String, Integer> text = entry.getValue();
p = new Paragraph()
.addTabStops(tabstops)
.add(text.getKey())
.add(new Tab())
.add(String.valueOf(text.getValue()))
.setAction(PdfAction.createGoTo(entry.getKey()));
document.add(p);
}
//Close document
document.close();
}
protected class TransparentImage implements IEventHandler {
protected PdfExtGState gState;
protected Image img;
public TransparentImage(Image img) {
this.img = img;
gState = new PdfExtGState().setFillOpacity(0.2f);
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.saveState().setExtGState(gState);
Canvas canvas = new Canvas(pdfCanvas, page.getPageSize());
canvas.add(img.scaleAbsolute(pageSize.getWidth(), pageSize.getHeight()));
pdfCanvas.restoreState();
pdfCanvas.release();
}
}
}
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.IO.Image;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Kernel.Pdf.Extgstate;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Hyphenation;
using iText.Layout.Properties;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E13_Compressed {
public const String SRC = "../../../resources/txt/jekyll_hyde.txt";
public const String IMG = "../../../resources/img/3132614.jpg";
public const String DEST = "../../../results/chapter07/jekyll_hyde_compressed.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E13_Compressed().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest, new WriterProperties().SetFullCompressionMode(true))
);
iText.Layout.Element.Image img = new Image(ImageDataFactory.Create(IMG));
IEventHandler handler = new C07E13_Compressed.TransparentImage(img);
pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
// Initialize document
Document document = new Document(pdf);
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3));
StreamReader sr = File.OpenText(SRC);
String name;
String line;
Paragraph p;
bool title = true;
int counter = 0;
IList<Util.Pair<String, Util.Pair<String, int>>> toc = new List<Util.Pair
<String, Util.Pair<String, int>>>();
while ((line = sr.ReadLine()) != null) {
p = new Paragraph(line);
p.SetKeepTogether(true);
if (title) {
name = String.Format("title{0:00}", counter++);
p.SetFont(bold).SetFontSize(12).SetKeepWithNext(true).SetDestination(name);
title = false;
document.Add(p);
toc.Add(new Util.Pair<string, Util.Pair<string,int>>(name, new Util.Pair<string,int>(line, pdf.GetNumberOfPages())));
}
else {
p.SetFirstLineIndent(36);
if (String.IsNullOrEmpty(line)) {
p.SetMarginBottom(12);
title = true;
}
else {
p.SetMarginBottom(0);
}
document.Add(p);
}
}
pdf.RemoveEventHandler(PdfDocumentEvent.START_PAGE, handler);
document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
p = new Paragraph().SetFont(bold).Add("Table of Contents").SetDestination("toc");
document.Add(p);
toc.RemoveAt(0);
IList<TabStop> tabstops = new List<TabStop>();
tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
foreach (Util.Pair<String, Util.Pair<String, int>> entry in toc) {
Util.Pair<String, int> text = entry.Value;
p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
(PdfAction.CreateGoTo(entry.Key));
document.Add(p);
}
//Close document
document.Close();
}
protected internal class TransparentImage : IEventHandler {
protected internal PdfExtGState gState;
protected internal iText.Layout.Element.Image img;
public TransparentImage(iText.Layout.Element.Image img) {
this.img = img;
this.gState = new PdfExtGState().SetFillOpacity(0.2f);
}
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdf);
pdfCanvas.SaveState().SetExtGState(this.gState);
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, page.GetPageSize());
canvas.Add(this.img.ScaleAbsolute(pageSize.GetWidth(), pageSize.GetHeight()));
pdfCanvas.RestoreState();
pdfCanvas.Release();
}
}
}
}
c07e14_encrypted
JAVA
package com.itextpdf.highlevel.chapter07;
import com.itextpdf.kernel.pdf.EncryptionConstants;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.WriterProperties;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
/**
* @author Bruno Lowagie (iText Software)
*/
public class C07E14_Encrypted {
public static final String DEST = "results/chapter07/encrypted.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C07E14_Encrypted().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
byte[] user = "It's Hyde".getBytes();
byte[] owner = "abcdefg".getBytes();
PdfDocument pdf = new PdfDocument(new PdfWriter(dest,
new WriterProperties().setStandardEncryption(user, owner,
EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_ASSEMBLY,
EncryptionConstants.ENCRYPTION_AES_256)));
Document document = new Document(pdf);
document.add(new Paragraph("Mr. Jekyll has a secret: he changes into Mr. Hyde."));
document.close();
}
}
C#
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace iText.Highlevel.Chapter07 {
/// <author>Bruno Lowagie (iText Software)</author>
public class C07E14_Encrypted {
public const String DEST = "../../../results/chapter07/encrypted.pdf";
public static void Main(String[] args) {
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new C07E14_Encrypted().CreatePdf(DEST);
}
public virtual void CreatePdf(String dest) {
byte[] user = GetBytes("It's Hyde");
string test = "test";
byte[] owner = GetBytes("abcdefg");
PdfDocument pdf = new PdfDocument(new PdfWriter(dest, new WriterProperties().SetStandardEncryption(user, owner
, EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_ASSEMBLY, EncryptionConstants.ENCRYPTION_AES_256
)));
Document document = new Document(pdf);
document.Add(new Paragraph("Mr. Jekyll has a secret: he changes into Mr. Hyde."));
document.Close();
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length];
for (int i = 0; i < str.Length; i++)
{
bytes[i] = System.Buffer.GetByte(str.ToCharArray(), 2 * i);
}
//System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
}
}
Resources
jekyll_hyde.txt
3132614.jpg
jekyll_hyde_bookmarked.pdf
Results
cmp_jekyll_hyde_page_orientation.pdf
cmp_jekyll_hyde_document_actions.pdf
cmp_jekyll_hyde_compressed.pdf