First look at the effect:
rely:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>Reference: https://blog.csdn.net/lcczpp/article/details/125424395
Relevant code:
package com.qxs.business.reform.utils.poi; import com.itextpdf.text.*; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.qxs.business.attachment.dto.PdfPageXofYEventHelper; import org.apache.commons.lang.StringUtils; import java.io.FileOutputStream; import java.util.concurrent.atomic.AtomicInteger; public class PdfUtils { private static BaseFont bfChinese; /** * plus black 22 */ private static Font head22Font; /** * plus black 16 */ private static Font headFont; /** * blue number 11 */ private static Font bodyBlueFont; /** * plus black 11 */ private static Font bodyBlockFont; /** * Regular size 11 */ private static Font textFont; /** * light blue */ private static BaseColor baseColor; static { try { bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); headFont = new com.itextpdf.text.Font(bfChinese, 16, com.itextpdf.text.Font.BOLD); head22Font = new com.itextpdf.text.Font(bfChinese, 22, com.itextpdf.text.Font.BOLD); bodyBlueFont = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.NORMAL); bodyBlueFont. setColor(55, 158, 253); bodyBlockFont = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.BOLD); textFont = new com.itextpdf.text.Font(bfChinese, 11, Font.NORMAL); // light blue baseColor = new BaseColor(55, 158, 253); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { try { // 1. Create a new document object Document document = new Document(PageSize. A4, 60, 60, 80, 80); String path = "C:/Users/admin/Desktop/1.pdf"; PdfWriter writer = PdfWriter. getInstance(document, new FileOutputStream(path)); writer.setStrictImageSequence(true); PdfPageXofYEventHelper pdfPageXofYEventHelper = new PdfPageXofYEventHelper("", bfChinese); document. open(); document. newPage(); pdfPageXofYEventHelper.setHead("test-test case"); writer.setPageEvent(pdfPageXofYEventHelper); PdfPTable table = new PdfPTable(4); setTable(table,90); table.setSplitLate(false); float[] columnWidths = {1f, 3f, 1f,3f}; table.setWidths(columnWidths); cellCenter(table,"the module it belongs to", bodyBlockFont); cellCenter(table,"wireless resource automatic"); cellCenter(table,"system id", bodyBlockFont); cellCenter(table, "12345"); cellCenter(table,"Level 1 function", bodyBlockFont); setColspan(table, "Qiuxia said", 3); cellCenter(table,"secondary function", bodyBlockFont); setColspan(table,"Guangdong Province",3); cellCenter(table,"Three-level function", bodyBlockFont); setColspan(table,"three warnings",3); cellCenter(table,"release date", bodyBlockFont); cellCenter(table,"2023-01-01"); cellCenter(table,"program version", bodyBlockFont); cellCenter(table,"2023-01-01"); cellCenter(table,"compiler", bodyBlockFont); cellCenter(table,"2023-01-01"); cellCenter(table,"Compilation time", bodyBlockFont); cellCenter(table,"2023-01-01"); cellCenter(table,"features", bodyBlockFont); setColspan(table,"2023-01-01",3); cellCenter(table,"Function operation and description", bodyBlockFont); PdfPCell pdfPCell = new PdfPCell(); pdfPCell.setColspan(3); pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE); pdfPCell.setMinimumHeight(25f); Paragraph elements = new Paragraph("This is the description", textFont); pdfPCell.addElement(elements); handleImage2Cell(pdfPCell); table.addCell(pdfPCell); cellCenter(table,"manufacturer responsible person", bodyBlockFont); cellCenter(table,"Qiu Xiaosong"); cellCenter(table,"Contact number", bodyBlockFont); cellCenter(table,"13983648272"); cellCenter(table,"Acceptance Date", bodyBlockFont); cellCenter(table,""); cellCenter(table,"Acceptance Comments", bodyBlockFont); cellCenter(table,"□ passed □ not passed"); cellCenter(table,"Acceptor", bodyBlockFont); setColspan(table,"",3); document. add(table); handleAnnex5Common(document, writer, 0); handleAnnex5Function(document, writer, 1); document. close(); writer. close(); } catch (Exception e) { e.printStackTrace(); } } private static void handleAnnex5Function(Document document, PdfWriter writer, int num) { try { Chapter chapter = getChapter(num, "Function Design"); document. add(chapter); Section section = getSection(chapter, "Third-level functions"); document. add(section); } catch (Exception e) { e.printStackTrace(); } } /** * * Dealing with Annex V public chapters * @param document document * @param writer writer */ private static void handleAnnex5Common(Document document, PdfWriter writer, int num) throws Exception { Chapter chapter = getChapter(1 + num, "Database Design"); Section section = getSection(chapter, "code table list"); //writeMsg2Section(section,common.getCodeTableMsg(), new float[]{0.5f,1f, 1f,1f}, new String[]{"Number", "Code Table Name", "Chinese Note", "New /modify/no change"}, new String[]{"tableName", "commentCn","status"},table1); Section section1 = getSection(chapter, "Entity Set List"); section1.add(getParagraph("subsystem common entity list", textFont, 10f, 10f)); //writeMsg2Section(section1,common.getSubsystemPublicMsg(), new float[]{0.5f,1f, 1f,1f}, new String[]{"serial number", "code table name", "Chinese comment", "new /modify/no change"}, new String[]{"tableName", "commentCn","status"},table2); section1.add(getParagraph("subsystem specific entity list", textFont, 10f, 10f)); //writeMsg2Section(section1,common.getSubsystemSpecificMsg(), new float[]{0.5f,1f, 1f,1f}, new String[]{"serial number", "code table name", "Chinese comment", "new /modify/no change"}, new String[]{"tableName", "commentCn","status"},table3); Section section2 = getSection(chapter, "The correspondence between entities and tables"); //writeMsg2Section(section2,common.getCorrespondenceMsg(), new float[]{0.5f,1f, 1f,1f}, new String[]{"serial number", "entity name", "table name", "description"} , new String[]{"tableName", "entityName","description"},tables); Section section3 = getSection(chapter, "Physical Data Model Diagram"); section3.add(getParagraph("Physical Data Model Diagram-qxs", textFont, 10f, 10f)); document. add(chapter); setImage(document, bodyBlueFont); Section section4 = getSection(chapter, "Table attribute description"); section4.add(getParagraph("table attribute description-qxs", textFont, 10f, 10f)); //handleAnnex5CommonField(dto, section4); document. add(section4); Section section5 = getSection(chapter, "Data volume distribution"); //writeMsg2Section(section5,common.getDistributionMsg(), new float[]{0.5f,1f, 1f,1f,1f}, new String[]{"serial number", "table name", "record length (bytes) ","Maximum number of records","Maximum number of bytes"}, new String[]{"tableName", "recordLength","maxRecordCount","maxByteCount"},tables); document. add(section5); Section section6 = getSection(chapter, "Data storage and access analysis"); handleAnnex5CommonAna("Data storage and access analysis-qxs", section6); document. add(section6); } private static void handleAnnex5CommonAna(String msg, Section section6) throws Exception { PdfPTable table = new PdfPTable(7); setTable(table); section6.add(getParagraph(msg, textFont, 10f, 10f)); float[] columnWidths = {0.5f,1f, 1f, 1f,1f, 1f, 1f}; table.setWidths(columnWidths); setRowSpan(table,"serial number",2); setRowSpan(table,"table name",2); setRowSpan(table,"storage period (days)",2); PdfPCell pdfPCell = getCellCenter("storage location"); pdfPCell.setBackgroundColor(baseColor); pdfPCell.setColspan(3); table.addCell(pdfPCell); setRowSpan(table,"access method",2); cellCenterAndSetGroundColor(table,"this site"); cellCenterAndSetGroundColor(table,"LAN server"); cellCenterAndSetGroundColor(table,"WAN server"); cellCenter(table, "--"); AtomicInteger atomicInteger = new AtomicInteger(1); for (int i = 0; i < 2; i ++ ) { cellCenter(table, atomicInteger. getAndIncrement() + ""); cellCenter(table, "table name"); cellCenter(table, "12"); String saveLocation = "What is this"; String s1 = ""; String s2 = ""; String s3 = ""; if(StringUtils.isNotBlank(saveLocation)){ if(saveLocation.contains("this site")){ s1 = "√"; } if(saveLocation.contains("LAN server")){ s2 = "√"; } if(saveLocation.contains("WAN server")){ s3 = "√"; } } cellCenter(table,s1); cellCenter(table, s2); cellCenter(table,s3); cellCenter(table, "This..."); } section6. add(table); } /** * The cell content is displayed in the center, and the light blue background is set * * @param table form * @param value content */ private static void cellCenterAndSetGroundColor(PdfPTable table, String value) { PdfPCell pdfPCell = getCellCenterAndSetGroundColor(value); table.addCell(pdfPCell); } /** * Cell k spans rows, and the content is displayed in the center * @param table table * @param value content * @param colspan number of columns */ private static void setRowSpan(PdfPTable table, String value, int colspan){ PdfPCell pdfPCell = getCellCenterAndSetGroundColor(value); pdfPCell.setBackgroundColor(baseColor); pdfPCell.setRowspan(colspan); table.addCell(pdfPCell); } /** * Center the cell * @param value data * @return cell */ private static PdfPCell getCellCenter(String value) { PdfPCell pdfPCell = new PdfPCell(); pdfPCell.setMinimumHeight(25f); pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE); Paragraph paragraph = new Paragraph(value, textFont); paragraph.setAlignment(Element.ALIGN_CENTER); //adapt row height paragraph. setLeading(12f); pdfPCell.addElement(paragraph); return pdfPCell; } /** * The cell content is centered, the background is light blue * @param value unit ge data * @return cell */ private static PdfPCell getCellCenterAndSetGroundColor( String value) { PdfPCell pdfPCell = getCellCenter(value); pdfPCell.setBackgroundColor(baseColor); return pdfPCell; } /** * Set the front and rear margins of the table * * @param table form */ private static void setTable(PdfPTable table) { setTable(table,100); } /** * Get the secondary label * * @param chapter level one label * @param value secondary tag value * @return secondary label */ private static Section getSection(Chapter chapter, String value) { Section section = chapter.addSection(getParagraph(value, headFont, 15f, 17f)); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); return section; } /** * Add paragraph content * * @param value content * @param font field * @param before front margin * @param after margin * @return Paragraph */ private static Paragraph getParagraph(String value, Font font, float before, float after) { Paragraph elements = new Paragraph(value, font); elements.setSpacingBefore(before); elements.setSpacingAfter(after); return elements; } /** * Get the first-level label * * @param num tag number * @param value tag data * @return first level label */ private static Chapter getChapter(int num, String value) { Chapter chapter = new Chapter(getParagraph(value, head22Font, 15f, 17f), num); // do not start a new page chapter.setTriggerNewPage(false); chapter.setNumberStyle(Chapter.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); return chapter; } /** * Process the picture and write it into the cell * @param pdfPCell cell * @throws Exception exception */ private static void handleImage2Cell(PdfPCell pdfPCell) throws Exception { String img = "C:\Users\admin\Downloads\img\1.jpg"; Image image = Image. getInstance(img); image.setSpacingBefore(10f); image.setSpacingAfter(5f); image.scalePercent(35000/image.getWidth()); //image.scaleAbsolute(350, 300); //image.setWidthPercentage(100f); image.setAlignment(Image.ALIGN_CENTER); //Fix the table to prevent the last picture at the bottom of the page from displaying abnormally PdfPTable pdfPTable = new PdfPTable(1); pdfPTable.setWidthPercentage(100f); PdfPCell pdfPCell1 = new PdfPCell(); pdfPCell1.setBorderWidthTop(0); pdfPCell1.setBorderWidthRight(0); pdfPCell1.setBorderWidthBottom(0); pdfPCell1.setBorderWidthLeft(0); pdfPCell1. addElement(image); pdfPTable.addCell(pdfPCell1); pdfPCell.addElement(pdfPTable); } /** * Set the front and rear margins of the table * * @param table form */ private static void setTable(PdfPTable table, int with) { table.setWidthPercentage(with); table.setSpacingBefore(10f); table.setSpacingAfter(10f); table.setSplitLate(true); table.setSplitRows(true); } /** * The cell content is displayed in the center * * @param table form * @param value content */ private static void cellCenter(PdfPTable table, String value) { cellCenter(table, value, textFont); } /** * The cell content is displayed in the center * @param table form * @param value content * @param font font * @return pdfPCell cell */ private static void cellCenter(PdfPTable table, String value, Font font) { PdfPCell pdfPCell = new PdfPCell(); pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE); pdfPCell.setMinimumHeight(25f); Paragraph paragraph = new Paragraph(value, font); paragraph.setAlignment(Element.ALIGN_CENTER); //adapt row height paragraph. setLeading(12f); pdfPCell.addElement(paragraph); table.addCell(pdfPCell); } /** * cell data * * @param value cell data * @return cell data */ private static PdfPCell getPdfPCell(String value) { return getPdfPCell(value, textFont); } /** * cell data * * @param value cell data * @param font font * @return cell data */ private static PdfPCell getPdfPCell(String value, Font font) { PdfPCell pdfPCell = new PdfPCell(); pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE); pdfPCell.setMinimumHeight(25f); Paragraph paragraph = new Paragraph(value, font); //adapt row height paragraph. setLeading(12f); pdfPCell.addElement(paragraph); return pdfPCell; } /** * Cell k spans columns, and the content is displayed in the center * @param table table * @param value content * @param colspan number of columns */ private static PdfPCell setColspan(PdfPTable table, String value, int colspan){ PdfPCell pdfPCell = getPdfPCell(value); pdfPCell.setColspan(colspan); pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(pdfPCell); return pdfPCell; } /** * Condition image * * @param document pdf * @param bodyFont font * @throws Exception exception * */ private static void setImage(Document document, Font bodyFont) throws Exception { setImage(document, bodyFont, 1); } /** * Condition image * * @param document pdf * @param bodyFont font * @throws Exception exception * */ private static void setImage(Document document, Font bodyFont, int num) throws Exception { String img = "C:\Users\admin\Downloads\img\1.jpg"; Image image = Image. getInstance(img); image.setAlignment(Image.ALIGN_CENTER); image.scalePercent(40000/image.getWidth()); //image.scaleAbsolute(400, 400); Paragraph elements = new Paragraph(); elements. add(image); document. add(elements); document.add(getParagraph("Qiu Xiaosong.pdf", bodyFont, 1f, 1f)); } }
package com.qxs.business.attachment.dto; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; /** * */ public class PdfPageXofYEventHelper extends PdfPageEventHelper { private BaseFont baseFont; private String head; private static String watermark = "This is a watermark"; private PdfGState gs; public PdfPageXofYEventHelper() { } public static void setWatermark(String str) { watermark = str; } public PdfPageXofYEventHelper(String head, BaseFont baseFont) { this.head = head; this. baseFont = baseFont; // Set watermark transparency PdfGState gs = new PdfGState(); // Set the fill font opacity to 0.09f gs.setFillOpacity(0.09f); this.gs = gs; } public void setHead(String head) { this.head = head; } /** * Override the onEndPage method in PdfPageEventHelper */ @Override public void onEndPage(PdfWriter writer, Document document) { //add title text StringBuffer underline = new StringBuffer(); for(int i = 0;i<80;i ++ ) { underline.append("_"); } Font bodyBlueFont = new Font(baseFont, 11, Font.NORMAL); Phrase contentPh = new Phrase(head,bodyBlueFont); Phrase underlinePh = new Phrase(underline.toString(),bodyBlueFont); Phrase pageNumberPh = new Phrase("- " + writer. getPageNumber() + " -",bodyBlueFont); //horizontal midpoint of the page float center = writer.getPageSize().getRight()/2; float top = writer.getPageSize().getTop() - 36; float bottom = writer.getPageSize().getBottom() + 10; /** The parameter xy refers to which store on the page the text is displayed on. alignment refers to the alignment of the text at the coordinate point */ // header ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER,contentPh,center,top,0); // header ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER,underlinePh,center,top-3,0); //page number ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER,pageNumberPh,center,bottom,0); PdfContentByte content = writer. getDirectContent(); // start content.beginText(); // Set watermark font parameters and size (font parameters, font encoding format, whether to embed font information into pdf (generally no need to embed), font size) content.setFontAndSize(baseFont, 55); // set transparency content.setGState(gs); // Set watermark alignment Watermark content X coordinate Y coordinate Rotation angle content.showTextAligned(Element.ALIGN_CENTER, watermark, center, 430, 45); // Set watermark color (gray) content.setColorFill(BaseColor.GRAY); //Finish content. endText(); } }