Directory
1. Preliminary preparation
1. Chinese font file
2. maven dependency
2. How to create a PDF document
3. Fill the business parameters through the fillable PDF template
1. Set up a fillable PDF form
2. Start the code, fill in the code and edit the PDF and save it as a file
1. Preliminary preparation
1, Chinese font file
This demonstration uses the iText 7 version, if there is no Chinese font, the generated PDF document will not be able to display the Chinese area.
The available free download URLs for PDFs are as follows:
- Alibaba Vector Icon Library: In addition to the icon library, this website also provides some free font libraries for download and use.
- Ziyou: Ziyou is a website that focuses on Chinese fonts, and provides some high-quality free fonts for download.
- Font China: Font China is a website that provides Chinese font downloads, including the works of many Chinese designers.
- Webmaster’s Home font library: Webmaster’s Home provides a large number of free font libraries, including various Chinese fonts and English fonts.
2, maven dependency
<dependencies> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.2.5</version> <type>pom</type> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>kernel</artifactId> <version>7.2.5</version> </dependency> </dependencies>
2. How to create a PDF document
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.canvas.PdfCanvas; import com.itextpdf.layout.Canvas; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Image; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.element.Table; import com.itextpdf.layout.properties.HorizontalAlignment; import com.itextpdf.layout.properties.TextAlignment; import com.itextpdf.layout.properties.UnitValue; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class CreatePdf { // file root directory public static String RootPath = "D:/files-pdf/"; // Set font file path // Note: If there is no Chinese font, the PDF content related to the Chinese area will not be displayed public static String fontPath = RootPath + "ZiTiQuanWeiJunHei-W1-2.ttf"; public static void main(String[] args) { String pdfName = "testContent.pdf"; // create PdfWriter and PdfDocument PdfWriter writer = null; try { writer = new PdfWriter(pdfName + ".pdf"); } catch (FileNotFoundException e) { System.out.println("Failed to create PdfWriter..."); e.printStackTrace(); return; } PdfDocument pdfDocument = new PdfDocument(writer); // Create Document Document document = new Document(pdfDocument); // set page margins documentMargins(document); // set header and footer headerAndFooter(pdfDocument); //Write the document content of the PDF body, this is the main writing position setContent(document); //add watermark addWatermark(pdfDocument); // close the object document.close(); //document document should be closed before output, otherwise it will prompt "java.nio.file.NoSuchFileException: editable.pdf" pdfDocument. close(); // Move the generated PDF file to the specified directory downloadPdf(RootPath, pdfName); } /** * Get the set font * * @return PdfFont font */ private static PdfFont getFont() { // set Chinese font PdfFont font = null; try { font = PdfFontFactory.createFont(fontPath); } catch (IOException e) { System.out.println("Font acquisition failed..."); e.printStackTrace(); return null; } return font; } /** * Set page margins * * @param document content document */ private static void documentMargins(Document document) { // up, right, down, left int margins = 80; document.setMargins(margins, margins, margins, margins); } /** * Set header and footer * * @param pdfDocument PDF document */ private static void headerAndFooter(PdfDocument pdfDocument) { pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE, new IEventHandler() { @Override public void handleEvent(Event event) { PdfDocumentEvent docEvent = (PdfDocumentEvent) event; PdfPage page = docEvent. getPage(); PdfCanvas canvas = new PdfCanvas(page); // create header Rectangle pageSize = page. getPageSize(); canvas.beginText() .setFontAndSize(getFont(), 10) .moveText(pageSize. getWidth() / 2, pageSize. getTop() - 20) .showText("This is the header") .endText(); // create footer canvas.beginText() .setFontAndSize(getFont(), 10) .moveText(pageSize.getWidth() / 2, pageSize.getBottom() + 20) .showText("This is the footer") .endText(); canvas. release(); } }); } /** * Add watermark * * @param pdfDocument PDF document * @throws MalformedURLException */ private static void addWatermark(PdfDocument pdfDocument) { // load watermark image String watermarkImage = RootPath + "zm5.jpg"; Image image = null; try { image = new Image(ImageDataFactory. create(watermarkImage)); } catch (MalformedURLException e) { System.out.println("Failed to get watermark image, e: " + e); e.printStackTrace(); return; } // Get the size of the PDF page, here is to use the page area as a reference, and then set the corresponding coordinates to fill the watermark Rectangle rectanglePageSize = pdfDocument. getDefaultPageSize(); // traverse each page, add watermark for (int i = 1; i <= pdfDocument. getNumberOfPages(); i ++ ) { //Create PDF canvas PdfCanvas pdfCanvas = new PdfCanvas(pdfDocument. getPage(i)); // Create a Canvas object, set the position and size Canvas canvas = new Canvas(pdfCanvas, rectanglePageSize, true); // Add a picture on the watermark canvas, and set the transparency and position // up, right, down, left image.setOpacity(0.8f).setMargins(600, 200, 0, 300); canvas. add(image); // Close the watermark canvas canvas. close(); } } /** * The generated PDF file is moved to the specified directory * * @param rootPath storage directory * @param pdfName PDF file name * @return */ private static String downloadPdf(String rootPath, String pdfName) { // Assume the generated PDF file path is sourcePath Path sourcePath = Paths.get(pdfName + ".pdf"); // Assume the target directory path is targetDirectoryPath Path targetDirectoryPath = Paths. get(rootPath); // move the file to the target directory Path targetPath = null; try { targetPath = Files.move(sourcePath, targetDirectoryPath.resolve(sourcePath.getFileName()), StandardCopyOption.REPLACE_EXISTING); // output success message System.out.println("The file moved successfully, the target path: " + targetPath); return targetPath.toString(); } catch (IOException e) { // output failure message System.out.println("File move failed, target path: " + targetPath); e.printStackTrace(); return null; } } /** * PDF main content * * @param document document */ private static void setContent(Document document) { // set Chinese font PdfFont font = getFont(); /******************************* Paragraph content is written by the Paragraph area************ *********************************/ // Create paragraph headings Paragraph paragraphTitle = new Paragraph().setFont(font); // setBold: set bold, setItalic: italic, setUnderline: underline paragraphTitle.add("This is a PDF test document").setBold().setFontSize(12); // Set the alignment of the paragraph to center paragraphTitle.setTextAlignment(TextAlignment.CENTER); document.add(paragraphTitle); // create an editable paragraph Paragraph nameOfStaff = new Paragraph().setFont(font).setFontSize(10); nameOfStaff.add("Name of Developer / Developer:"); document. add(nameOfStaff); Paragraph fullname = new Paragraph().setFont(font).setFontSize(10); fullname.add("____________________(Note: Please write full name)"); document. add(fullname); Paragraph paragraph1 = new Paragraph().setFont(font).setFontSize(9); paragraph1.add("This is the content of the paragraph! This is the content of the paragraph! This is the content of the paragraph! This is the content of the paragraph! This is the content of the paragraph! This is the content of the paragraph! This is the content of the paragraph! This is the content of the paragraph! This is the content of the paragraph !" + "This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph content!" + "This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph content!" + "This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph content!" + "This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph! This is a paragraph content!"); document. add(paragraph1); Paragraph declare = new Paragraph().setFont(font).setFontSize(9); declare.add("I hereby declare that:"); document. add(declare); Paragraph section = new Paragraph().setFont(font).setFontSize(9).setBold().setUnderline(); section.add("Multiple option declaration confirmation! Multiple option declaration confirmation!"); document. add(section); // create a list with checkboxes Paragraph paragraph2 = new Paragraph().setFont(font).setFontSize(9); paragraph2.add("(Please tick in the box as appropriate)").add("\\ "); paragraph2.add("declaration content 1...declaration content 1...declaration content 1...declaration content 1...declaration content 1...declaration content 1...").add(\ "\\ "); paragraph2.add("Declaration content 2...Declaration content 2...Declaration content 2...Declaration content 2...Declaration content 2...Declaration content 2...").add(\ "\\ "); document. add(paragraph2); /****************************** Table is written by Table area************ *******************************/ // Create a table and set the number of columns and default width Table table = new Table(4); // table.setMaxWidth(1000); //fixed width // table.setAutoLayout(); // Adaptive width according to the content table.setWidth(UnitValue.createPercentValue(100)); //The total width of the page is fixed // Add table header (merge 4 columns) Cell titleCell = new Cell(1, 4); // create text object titleCell.add(new Paragraph("Table Title")); titleCell.setTextAlignment(TextAlignment.CENTER); table.addHeaderCell(titleCell); // add header table.addHeaderCell("Header 1"); table.addHeaderCell("Header 2"); table.addHeaderCell("Header 3"); table.addHeaderCell("Header 4"); // add table content for (int i = 0; i < 3; i ++ ) { for (int j = 0; j < 4; j ++ ) { Cell cell = new Cell() .setFont(font) .add(new Paragraph("Line " + (i + 1) + ", Col " + (j + 1))) .setWidth(UnitValue.createPercentValue(25)); table. addCell(cell); } } // set table style table.setHorizontalAlignment(HorizontalAlignment.CENTER); // add the table to the document document. add(table); /****************************** Content Area Writing END *************** *******************************/ } }
3. Fill the business parameters with the fillable PDF template
1. Set up a fillable PDF form
As for the editor to find it by itself, most of the free ones will add watermarks.
After the setting is successful, as shown in the figure below, the editable area is highlighted
2. Open the code, fill the editable PDF with the code and save it as a file
import com.itextpdf.forms.PdfAcroForm; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.PdfWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; public class FillingPdfTemplate { // file root directory public static String RootPath = "D:/files-pdf/"; // Set font file path // Note: If there is no Chinese font, the PDF content related to the Chinese area will not be displayed public static String fontPath = RootPath + "ZiTiQuanWeiJunHei-W1-2.ttf"; public static void main(String[] args) { Map<String, String> mapParam = new HashMap<>(); mapParam.put("fullname", "someone"); mapParam.put("Check Box1","On"); mapParam.put("Check Box2", "Off"); mapParam.put("account1", "account1"); mapParam.put("broker1", "broker1"); mapParam.put("number1", "number1"); mapParam.put("security1", "security1"); mapParam.put("sharehold1", "sharehold1"); mapParam.put("clp1", "clp1"); mapParam.put("shares1", "shares1"); mapParam.put("sharehold3", ""); mapParam.put("clp3", ""); mapParam.put("shares3", ""); mapParam.put("name1", "someone"); mapParam.put("position", "XXX Advanced"); mapParam.put("company", "Shenzhen XXX Technology Co., Ltd."); mapParam.put("date", "2023-05-24"); String templatePdfPath = RootPath + "Acrobat-demo.pdf"; String destPdfPath = RootPath + "Acrobat-demo-result.pdf"; replaceTextFieldPdf(templatePdfPath, destPdfPath, mapParam); } /** * Get the set font * * @return PdfFont font */ private static PdfFont getFont() { // set Chinese font PdfFont font = null; try { font = PdfFontFactory.createFont(fontPath); } catch (IOException e) { System.out.println("Font acquisition failed..."); e.printStackTrace(); return null; } return font; } /** * Replace PDF text form field variables * * @param templatePdfPath The full path of the pdf to be replaced * @param params replacement parameters * @param destPdfPath The full path of the saved PDF after replacement * @throws IOException */ public static final void replaceTextFieldPdf(String templatePdfPath, String destPdfPath, Map<String, String> params) { PdfDocument pdfDoc = null; try { pdfDoc = new PdfDocument(new PdfReader(templatePdfPath), new PdfWriter(destPdfPath)); } catch (IOException e) { e.printStackTrace(); } // Get form information PdfAcroForm pdfAcroForm = PdfAcroForm. getAcroForm(pdfDoc, true); //Loop through the filled preset values Set<Map.Entry<String, String>> entries = params.entrySet(); entries. stream(). forEach(entry -> { if(pdfAcroForm. getField(entry. getKey()) != null){ // set the value of the form field //Check box type: 1 check, 2 circles, 3 forks, 4 diamonds, 5 squares, 6 stars //If you don't want the check box to be selected, set it to "Off", set it to "On", pay attention to capitalization pdfAcroForm.getField(entry.getKey()).setCheckType(1).setValue(entry.getValue(), true).setFont(getFont()); } }); // add form fields // PdfTextFormField textField = PdfFormField.createText(pdfDoc, new Rectangle(100, 100, 200, 20), "newField", ""); //pdfAcroForm.addField(textField); //The form is flattened, and the document generated after setting can no longer be edited //pdfAcroForm.flattenFields(); pdfDoc. close(); } }