引入jar包
<dependencies> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.2.5</version> <type>pom</type> </dependency> </dependencies>
代码
package org.example.TestPdf; import com.itextpdf.forms.PdfAcroForm; import com.itextpdf.kernel.colors.DeviceRgb; 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.util.HashMap; import java.util.Map; /** * @author pei */ public class Mypdf { public static void main(String[] args) { PdfDocument document =null; try { document = new PdfDocument(new PdfReader("C:\\Users\\pei\\Desktop\\888999.pdf"),new PdfWriter("C:\\Users\\pei\\Desktop\\666666.pdf")); System.out.println("document==="+document); PdfAcroForm form = PdfAcroForm.getAcroForm(document,false); System.out.println("from=="+form); // 设置字体 times_roman PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED); //设置颜色 DeviceRgb color = new DeviceRgb(0,0,0); //文本填充 Map<String,String> map = new HashMap<>(); map.put("name","张三"); map.put("name1","李四"); for(Map.Entry<String,String> entry:map.entrySet()){ System.out.println("key==="+entry.getKey()); form.getFormFields().get(entry.getKey()).setValue(entry.getValue()).setColor(color).setFont(font); } //清除格式 form.flattenFields(); }catch (Exception e){ e.printStackTrace(); }finally { if(null !=document){ //关闭流 document.close(); } } } }
原文地址
https://blog.csdn.net/FBB360JAVA/article/details/131449577
标签:kernel,java,填充,itextpdf,import,pdf,document,com From: https://www.cnblogs.com/xianz666/p/18549435