itext7学习笔记——第4章实践&example

时间:2022-05-08 14:13:31

    本章的例子,请参考我翻译的博文:itext7学习笔记——第4章,里面有详细的解释,有什么不懂得也可以评论或者私信我!

例子1:文本注释

    在一个Paragraph之前添加最简单的文本注释,代码如下:

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfTextAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

import java.io.File;
import java.io.IOException;

/**
* Simple text annotation example.
*/

public class C04E01_01_TextAnnotation {

public static final String DEST = "results/chapter04/text_annotation.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E01_01_TextAnnotation().createPdf(DEST);
}

public void createPdf(String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

//Initialize document
Document document = new Document(pdf);
document.add(new Paragraph("The example of text annotation."));

//Create text annotation
PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(20, 800, 0, 0))
.setColor(Color.GREEN)
.setTitle(new PdfString("iText"))
.setContents("With iText, you can truly take your documentation needs to the next level.")
.setOpen(true);
pdf.getFirstPage().addAnnotation(ann);

//Close document
document.close();

}
}

例子2:链接注释

    在”here”上面添加链接注释,并创建链接到itext官网,代码如下:

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.annot.PdfLinkAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Link;
import com.itextpdf.layout.element.Paragraph;

import java.io.File;
import java.io.IOException;

/**
* Simple link annotation example.
*/

public class C04E01_02_LinkAnnotation {

public static final String DEST = "results/chapter04/link_annotation.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E01_02_LinkAnnotation().createPdf(DEST);
}

public void createPdf(String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

//Initialize document
Document document = new Document(pdf);

//Create link annotation
PdfLinkAnnotation annotation = new PdfLinkAnnotation(new Rectangle(0, 0))
.setAction(PdfAction.createURI("http://itextpdf.com/"));
Link link = new Link("here", annotation);
Paragraph p = new Paragraph("The example of link annotation. Click ")
.add(link.setUnderline())
.add(" to learn more...");
document.add(p);

//Close document
document.close();

}
}

例子3:线注释

    在一个pdf文档里面添加线注释,代码如下:

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfLineAnnotation;

import java.io.File;
import java.io.IOException;

/**
* Simple line annotation example.
*/

public class C04E01_03_LineAnnotation {

public static final String DEST = "results/chapter04/line_annotation.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E01_03_LineAnnotation().createPdf(DEST);
}

public void createPdf(String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfPage page = pdf.addNewPage();

PdfArray lineEndings = new PdfArray();
lineEndings.add(new PdfName("Diamond"));
lineEndings.add(new PdfName("Diamond"));

//Create line annotation with inside caption
PdfAnnotation annotation = new PdfLineAnnotation(
new Rectangle(0, 0),
new float[]{20, 790, page.getPageSize().getWidth() - 20, 790})
.setLineEndingStyles((lineEndings))
.setContentsAsCaption(true)
.setTitle(new PdfString("iText"))
.setContents("The example of line annotation")
.setColor(Color.BLUE);
page.addAnnotation(annotation);

//Close document
pdf.close();

}
}

例子4:标记注释

    在pdf里面创建标记注释,代码如下

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfArray;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfTextMarkupAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

import java.io.File;
import java.io.IOException;

/**
* Simple text markup annotation example.
*/

public class C04E01_04_TextMarkupAnnotation {

public static final String DEST = "results/chapter04/textmarkup_annotation.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E01_04_TextMarkupAnnotation().createPdf(DEST);
}

public void createPdf(String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

//Initialize document
Document document = new Document(pdf);

Paragraph p = new Paragraph("The example of text markup annotation.");
document.showTextAligned(p, 20, 795, 1, TextAlignment.LEFT,
VerticalAlignment.MIDDLE, 0);

//Create text markup annotation
PdfAnnotation ann = PdfTextMarkupAnnotation.createHighLight(new Rectangle(105, 790, 64, 10),
new float[]{169, 790, 105, 790, 169, 800, 105, 800})
.setColor(Color.YELLOW)
.setTitle(new PdfString("Hello!"))
.setContents(new PdfString("I'm a popup."))
.setTitle(new PdfString("iText"))
.setOpen(true)
.setRectangle(new PdfArray(new float[]{100, 600, 200, 100}));
pdf.getFirstPage().addAnnotation(ann);

//Close document
document.close();

}
}

例子5:创建表单

    在pdf里面创建工作信息表单,代码如下:

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfButtonFormField;
import com.itextpdf.forms.fields.PdfChoiceFormField;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.forms.fields.PdfTextFormField;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;

import java.io.File;
import java.io.IOException;

/**
* Simple widget annotation example.
*/

public class C04E02_JobApplication {

public static final String DEST = "results/chapter04/job_application.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E02_JobApplication().createPdf(DEST);
}

public void createPdf(String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PageSize ps = PageSize.A4;
pdf.setDefaultPageSize(ps);

// Initialize document
Document document = new Document(pdf);

C04E02_JobApplication.addAcroForm(document);

//Close document
document.close();

}

public static PdfAcroForm addAcroForm(Document doc) {

Paragraph title = new Paragraph("Application for employment")
.setTextAlignment(TextAlignment.CENTER)
.setFontSize(16);
doc.add(title);
doc.add(new Paragraph("Full name:").setFontSize(12));
doc.add(new Paragraph("Native language: English French German Russian Spanish").setFontSize(12));
doc.add(new Paragraph("Experience in: cooking driving software development").setFontSize(12));
doc.add(new Paragraph("Preferred working shift:").setFontSize(12));
doc.add(new Paragraph("Additional information:").setFontSize(12));

//Add acroform
PdfAcroForm form = PdfAcroForm.getAcroForm(doc.getPdfDocument(), true);

//Create text field
PdfTextFormField nameField = PdfTextFormField.createText(doc.getPdfDocument(),
new Rectangle(99, 753, 425, 15), "name", "");
form.addField(nameField);

//Create radio buttons
PdfButtonFormField group = PdfFormField.createRadioGroup(doc.getPdfDocument(), "language", "");
PdfFormField.createRadioButton(doc.getPdfDocument(), new Rectangle(130, 728, 15, 15), group, "English");
PdfFormField.createRadioButton(doc.getPdfDocument(), new Rectangle(200, 728, 15, 15), group, "French");
PdfFormField.createRadioButton(doc.getPdfDocument(), new Rectangle(260, 728, 15, 15), group, "German");
PdfFormField.createRadioButton(doc.getPdfDocument(), new Rectangle(330, 728, 15, 15), group, "Russian");
PdfFormField.createRadioButton(doc.getPdfDocument(), new Rectangle(400, 728, 15, 15), group, "Spanish");
form.addField(group);

//Create checkboxes
for (int i = 0; i < 3; i++) {
PdfButtonFormField checkField = PdfFormField.createCheckBox(doc.getPdfDocument(), new Rectangle(119 + i * 69, 701, 15, 15),
"experience".concat(String.valueOf(i+1)), "Off", PdfFormField.TYPE_CHECK);
form.addField(checkField);
}

//Create combobox
String[] options = {"Any", "6.30 am - 2.30 pm", "1.30 pm - 9.30 pm"};
PdfChoiceFormField choiceField = PdfFormField.createComboBox(doc.getPdfDocument(), new Rectangle(163, 676, 115, 15),
"shift", "Any", options);
form.addField(choiceField);

//Create multiline text field
PdfTextFormField infoField = PdfTextFormField.createMultilineText(doc.getPdfDocument(),
new Rectangle(158, 625, 366, 40), "info", "");
form.addField(infoField);

//Create push button field
PdfButtonFormField button = PdfFormField.createPushButton(doc.getPdfDocument(),
new Rectangle(479, 594, 45, 15), "reset", "RESET");
button.setAction(PdfAction.createResetForm(new String[] {"name", "language", "experience1", "experience2", "experience3", "shift", "info"}, 0));
form.addField(button);

return form;

}
}

例子6:填充表单

    创建完表单以后,填充表单内容,代码如下:

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
* Simple filling out form example.
*/

public class C04E03_CreateAndFill {

public static final String DEST = "results/chapter04/create_and_fill.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E03_CreateAndFill().createPdf(DEST);
}

public void createPdf(String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

// Initialize document
Document doc = new Document(pdf);

PdfAcroForm form = C04E02_JobApplication.addAcroForm(doc);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue("James Bond");
fields.get("language").setValue("English");
fields.get("experience1").setValue("Off");
fields.get("experience2").setValue("Yes");
fields.get("experience3").setValue("Yes");
fields.get("shift").setValue("Any");
fields.get("info").setValue("I was 38 years old when I became an MI6 agent.");

doc.close();

}
}

例子7:预填充表单

    打开已存在的pdf,预填充表单内容,代码如下:

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;

import java.io.*;
import java.util.Map;

/**
* Simple filling out form example.
*/

public class C04E04_FillForm {

public static final String SRC = "src/main/resources/pdf/job_application.pdf";
public static final String DEST = "results/chapter04/fill_form.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E04_FillForm().manipulatePdf(SRC, DEST);
}

public void manipulatePdf(String src, String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));


PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue("James Bond");
fields.get("language").setValue("English");
fields.get("experience1").setValue("Off");
fields.get("experience2").setValue("Yes");
fields.get("experience3").setValue("Yes");
fields.get("shift").setValue("Any");
fields.get("info").setValue("I was 38 years old when I became an MI6 agent.");

pdf.close();

}
}

例子8:锁定表单

    打开已存在的pdf,锁定表单填充的内容,使之不能被编辑,代码如下:

/**
* Created by ASUS on 2017/9/12.
*/

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;

import java.io.*;
import java.util.Map;

/**
* Simple filling out form example.
*/

public class C04E05_FlattenForm {

public static final String SRC = "src/main/resources/pdf/job_application.pdf";
public static final String DEST = "results/chapter04/flatten_form.pdf";

public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C04E05_FlattenForm().manipulatePdf(SRC, DEST);
}

public void manipulatePdf(String src, String dest) throws IOException {

//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));


PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue("James Bond");
fields.get("language").setValue("English");
fields.get("experience1").setValue("Off");
fields.get("experience2").setValue("Yes");
fields.get("experience3").setValue("Yes");
fields.get("shift").setValue("Any");
fields.get("info").setValue("I was 38 years old when I became an MI6 agent.");
form.flattenFields();

pdf.close();

}
}

Example代码下载

    本章代码可在如下地址下载(IDEA工程):iText7——第四章源代码工程