itextpdf reads the specified area and writes the specified area of the new file

 <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

Reference: Step by step IText.Sharp Chunk Phrase Paragraph List usage – cdboy – Blog Park (cnblogs.com)

1. Read the specified area of the template

2. Output the template content according to paragraphs

3. Output the specified content in the specified area

package com.example.demo.pdf;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.*;

import java.io.*;
import java.text.MessageFormat;

public class MyPDF {

public static void main(String[] args) throws IOException, DocumentException {
String pdf = "E:\Contract test template.pdf";
String newPdf = "E:\Contract Test 2023.pdf";

//Single page read in separate areas
String pdfReaderByReacngle = getPdfReaderByReacngle(pdf, 0.0F, 750.0F, 595.3F, 841.9F);
// Line breaks should be retained here, and a paragraph array should be cut according to the line breaks.
String pdfReaderByReacngle2 = getPdfReaderByReacngle(pdf, 0.0F, 510.0F, 595.3F, 750.0F).replace("\r\\
","").replace("\\
",\ "");
System.out.println(pdfReaderByReacngle2);

String s = getPdfReaderByReacngle(pdf, 0.0F, 400.0F, 595.3F, 510.0F).replace("Company name:", "Company name: {0}").replace("Responsible person:\ ", "Responsible person: {1}").replace("Date: _year_month_day", "Date: {2}");
String a = "xxxx Co., Ltd.";
String name = "xxx";
String date = "October 21, 2023";
// placeholder replacement
String pdfReaderByReacngle3 = MessageFormat.format(s,a,name,date);

System.out.println(pdfReaderByReacngle3);

//Create text object
Document document = new Document(PageSize.A4);
File attachPdfFile = new File(newPdf);
attachPdfFile.createNewFile();

//PdfWriter is iText's editor for editing PDF documents
//Create a Writer instance for this Document
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(attachPdfFile));

//Open document
document.open();

//Insert paragraph text
//Set the Chinese font and boldness is also set here
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);

/*------------------------------1----------------- --------------------------*/
Paragraph textgraph = new Paragraph(pdfReaderByReacngle,fontChinese);
//Align left
textgraph.setAlignment(Element.ALIGN_CENTER);

//The spacing before and after the paragraph
textgraph.setSpacingBefore(50);

document.add(textgraph);
/*------------------------------2----------------- --------------------------*/
Paragraph textgraph2 = new Paragraph(pdfReaderByReacngle2,fontChinese);
//Align left
textgraph2.setAlignment(Element.ALIGN_LEFT);

textgraph2.setFirstLineIndent(25);
//The spacing before and after the paragraph
// textgraph.setSpacingAfter(50);
textgraph2.setSpacingBefore(20);

document.add(textgraph2);
/*---------------------------------3. Fixed area-------------- --------------------------------*/
Paragraph textgraph3 = new Paragraph(pdfReaderByReacngle3,fontChinese);
//Align left
textgraph3.setAlignment(Element.ALIGN_CENTER);

//The spacing before and after the paragraph
//textgraph3.setSpacingAfter(50);
textgraph3.setSpacingBefore(20);

Rectangle rects3 = new Rectangle(400.0F, 400.0F, 595.3F, 550.0F);//Text box position
writer.getDirectContent().rectangle(rects3);

ColumnText ct = new ColumnText(writer.getDirectContent());
ct.addElement(textgraph3);
ct.setSimpleColumn(rects3);
ct.go();
/*---------------------------------4----------------- --------------------------*/
//Close document
document.close();

//todo itextpdf read and write files
}

private static String getStringByItext(String pdf, String result) throws IOException {
PdfReader pdfReader = new PdfReader(pdf);

pdfReader.setAppendable(true);
// Parse the PDF file and obtain the page number of the PDF document
int size = pdfReader.getNumberOfPages();
for(int i = 1; i < size + 1;i= i + 1){
//Read PDF text page by page
String pageStr = PdfTextExtractor.getTextFromPage(pdfReader,i);
result = result + pageStr;

}
pdfReader.close();
return result;
}

//Read the content within the specified range
private static String getPdfReaderByReacngle(String pdf,float leftx,float lefty,float rightx,float righty) throws IOException {
PdfReader pdfReader = new PdfReader(pdf);
String pageContent = "";
Rectangle rect = new Rectangle(leftx, lefty, rightx, righty);
RenderFilter filter = new RegionTextRenderFilter(rect);

int pageNum = pdfReader.getNumberOfPages();
TextExtractionStrategy strategy;
for (int i = 1; i <= pageNum; i + + ) {
strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter);
pageContent + =PdfTextExtractor.getTextFromPage(pdfReader, i, strategy);
}
return pageContent;
}

//Get the position parameters of the specified page to facilitate area division
private static PdfReader getPdfReader(String pdf,int num) throws IOException {
PdfReader pdfReader = new PdfReader(pdf);

Rectangle pageSize = pdfReader.getPageSize(num);
float height = pageSize.getHeight();
float width = pageSize.getWidth();
float left = pageSize.getLeft();
float right = pageSize.getRight();
float top = pageSize.getTop();
return pdfReader;
}
}

2. Make certain parts of a paragraph bold

Performance

Template

public class MyPdf2 {
public static void main(String[] args) throws IOException, DocumentException {

String pdf = "E:\Contract template.pdf";
String newPdf = "E:\Contract Test 2023.pdf";
FileOutputStream fileOutputStream = new FileOutputStream(new File(newPdf));

PdfReader pdfReader = new PdfReader(pdf);


BaseFont title = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font titleFontChinese = new Font(title, 12, Font.BOLD);

BaseFont first = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font firstChinese = new Font(first, 14, Font.NORMAL);

BaseFont second = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font secondChinese = new Font(second, 14, Font.BOLD);


Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
document.open();

String s = "";

for (int i = 1; i < pdfReader.getNumberOfPages() + 1; i + + ) {
s + =PdfTextExtractor.getTextFromPage(pdfReader,i);
}
String[] split = s.replaceAll("\\
","").split("\|");
for (int i = 0; i < split.length; i + + ) {
if(i==0) {
Paragraph elements = new Paragraph(split[i], titleFontChinese);
elements.setAlignment(Element.ALIGN_CENTER);
document.add(elements);
} else if (i==2 |i==3) {
String s1 = split[i];
String[] split1 = s1.split("@");
//Short sentence
Phrase phrase = new Phrase();
phrase.setLeading(25f);
phrase.add(Chunk.SPACETABBING);
phrase.add(new Chunk(split1[0],firstChinese));
phrase.add(new Chunk(split1[1],secondChinese));
phrase.add(new Chunk(split1[2],firstChinese));
phrase.add(Chunk.NEWLINE);
document.add(phrase);
}else if (i==5) {
Paragraph elements = new Paragraph(split[i], firstChinese);
elements.setAlignment(Element.ALIGN_LEFT);
elements.setFirstLineIndent(25);
document.add(elements);
}else{
Paragraph elements = new Paragraph(split[i], firstChinese);
elements.setAlignment(Element.ALIGN_LEFT);
elements.setFirstLineIndent(25);
document.add(elements);
}
}

document.close();

}
}

3. Modify on the basis of 2 to achieve indentation of the first line of the paragraph and maintain consistent paragraph spacing.

Effect

public class MyPdf2 {
public static void main(String[] args) throws IOException, DocumentException {

String pdf = "E:\Contract template.pdf";
String newPdf = "E:\Contract Test 2024.pdf";
FileOutputStream fileOutputStream = new FileOutputStream(new File(newPdf));

PdfReader pdfReader = new PdfReader(pdf);


BaseFont title = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font titleFontChinese = new Font(title, 12, Font.BOLD);

BaseFont first = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font firstChinese = new Font(first, 14, Font.NORMAL);

BaseFont second = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font secondChinese = new Font(second, 14, Font.BOLD);


Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
document.open();

String s = "";

for (int i = 1; i < pdfReader.getNumberOfPages() + 1; i + + ) {
s + =PdfTextExtractor.getTextFromPage(pdfReader,i);
}
String[] split = s.replaceAll("\\
","").split("\|");
for (int i = 0; i < split.length; i + + ) {
if(i==0) {
Paragraph elements = new Paragraph(split[i], titleFontChinese);
elements.setAlignment(Element.ALIGN_CENTER);
document.add(elements);
document.add(Chunk.NEWLINE);
} else if (i==2 |i==3) {
String s1 = split[i];
String[] split1 = s1.split("@");
//Paragraph
Paragraph paragraph = new Paragraph();
//Short sentence
Phrase phrase = new Phrase();
//Chunk block
Chunk chunk1 = new Chunk(split1[0], firstChinese);
//chunk1.setCharacterSpacing(1.5f);
Chunk chunk2 = new Chunk(split1[1], secondChinese);
//chunk2.setCharacterSpacing(1.5f);
Chunk chunk3 = new Chunk(split1[2], firstChinese);
//chunk3.setCharacterSpacing(1.5f);
phrase.add(chunk1);
phrase.add(chunk2);
phrase.add(chunk3);
paragraph.add(phrase);
\t\t\t\t//First line indent
paragraph.setFirstLineIndent(25);
//Set the interline data to be consistent with other paragraphs
paragraph.setLeading(21f);
paragraph.setAlignment(Element.ALIGN_LEFT);
document.add(paragraph);
}else if (i==5) {
Paragraph elements = new Paragraph(split[i], firstChinese);
elements.setAlignment(Element.ALIGN_LEFT);
elements.setFirstLineIndent(25);
document.add(elements);


            //Insert the picture at the specified position. By default, the area is specified on the last page of the PDF.
            /*---------------------------------4----------------- --------------------------*/
//Image image = Image.getInstance("E:\Study Notes\lxl.jpg");
//image.scaleAbsolute(100,50); //Zoom
//image.setAbsolutePosition(495f,270f);//Coordinates
writer is the PdfWriter writer above
//PdfContentByte directContent = writer.getDirectContent();
//directContent.addImage(image);
}else{
Paragraph elements = new Paragraph(split[i], firstChinese);
//Get the default value of other paragraphs and set it to block line 71
float leading = elements.getLeading();
System.out.println("leading:" + leading); //21
elements.setAlignment(Element.ALIGN_LEFT);
elements.setFirstLineIndent(25);
document.add(elements);
//document.add(Chunk.NEWLINE);
}
}

document.close();

}
}

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 137998 people are learning the system