itext 动态的填充pdf

iText是用于生成PDF文档的Java类库,可生成PDF、rtf文档,还能将XML、Html文件转化为PDF。本文整理了PDF模版填充、多个PDF合并、分割等操作实例,还介绍了在Servlet中调用IText返回给客户端的方法,最后分享了工作中动态选中选框的解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

     下面简单的整理几个操作pdf相关实例。

1.PDF模版填充

     首先需要有一个pdf文件作为模版,可以用如adobe acrobat等工具,添加几个文本域在pdf中,下面就是模版完成后的部分截图。

Java代码  

 * @throws IOException 
 * @throws DocumentException 
 */  
@SuppressWarnings("unchecked")  
@Test  
public void fillTemplate()  
        throws IOException, DocumentException {  
    PdfReader reader = new PdfReader(templateFile); // 模版文件目录  
    PdfStamper ps = new PdfStamper(reader, new FileOutputStream(  
            "f:/fillTemplate.pdf")); // 生成的输出流  
    // ByteArrayOutputStream bos = new ByteArrayOutputStream();  
    // PdfStamper ps = new PdfStamper(reader, bos);  
  
    AcroFields s = ps.getAcroFields();  
  
    Map<String, Object> fieldMap = s.getFields(); // pdf表单相关信息展示  
    for (Map.Entry<String, Object> entry : fieldMap.entrySet()) {  
        String name = entry.getKey(); // name就是pdf模版中各个文本域的名字  
        Item item = (Item) entry.getValue();  
        System.out.println("[name]:" + name + ", [value]: " + item);  
    }  
  
    s.setField("CUSTOMERNAME", "as该多好公司");  
    s.setField("TEL", "123456asdzxc");  
    s.setField("CONTACT", "我是联系人123");  
  
    ps.setFormFlattening(true); // 这句不能少  
    ps.close();  
    reader.close();  
} 

输出的pdf文件内容:

注:默认情况下如果填充的字段值含中文时,将提示报错,这是因为没有IText相应的中文语言包,需要下载亚洲语言包,ITextAsian.jar。

如不想生成文件流(临时文件),可用ByteArrayOutputStream代替。

2.多个PDF合并

Java代码  

/** 
 * 多个PDF合并功能 
 *  
 * @param files 
 *            多个PDF的文件路径 
 * @param os 
 *            生成的输出流 
 */  
public static void mergePdfFiles(String[] files, OutputStream os) {  
    try {  
        Document document = new Document(  
                new PdfReader(files[0]).getPageSize(1));  
        PdfCopy copy = new PdfCopy(document, os);  
        document.open();  
        for (int i = 0; i < files.length; i++) {  
            PdfReader reader = new PdfReader(files[i]);  
            int n = reader.getNumberOfPages();  
            for (int j = 1; j <= n; j++) {  
                document.newPage();  
                PdfImportedPage page = copy.getImportedPage(reader, j);  
                copy.addPage(page);  
            }  
        }  
        document.close();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } catch (DocumentException e) {  
        e.printStackTrace();  
    }  
}  

如果想要直接合并输出流,可以换成输出流的集合

Java代码  

/** 
 * 多个PDF合并功能  
 * @param osList 
 * @param os 
 */  
public static void mergePdfFiles(List<ByteArrayOutputStream> osList,  
        OutputStream os) {  
    try {  
        Document document = new Document(new PdfReader(osList.get(0)  
                .toByteArray()).getPageSize(1));  
        PdfCopy copy = new PdfCopy(document, os);  
        document.open();  
        for (int i = 0; i < osList.size(); i++) {  
            PdfReader reader = new PdfReader(osList.get(i).toByteArray());  
            int n = reader.getNumberOfPages();  
            for (int j = 1; j <= n; j++) {  
                document.newPage();  
                PdfImportedPage page = copy.getImportedPage(reader, j);  
                copy.addPage(page);  
            }  
        }  
        document.close();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } catch (DocumentException e) {  
        e.printStackTrace();  
    }  
}  

3.PDF分割

Java代码  

/** 
 * 单个Pdf文件分割成N个文件 
 *  
 * @param filepath 
 * @param N 
 */  
public static void partitionPdfFile(String filepath, int N) {  
    Document document = null;  
    PdfCopy copy = null;  
  
    try {  
        PdfReader reader = new PdfReader(filepath);  
        int n = reader.getNumberOfPages();  
        if (n < N) {  
            System.out.println("The document does not have " + N  
                    + " pages to partition !");  
            return;  
        }  
        int size = n / N;  
        String staticpath = filepath.substring(0,  
                filepath.lastIndexOf("\\") + 1);  
        String savepath = null;  
        List<String> savepaths = new ArrayList<String>();  
        for (int i = 1; i <= N; i++) {  
            if (i < 10) {  
                savepath = filepath.substring(  
                        filepath.lastIndexOf("\\") + 1,  
                        filepath.length() - 4);  
                savepath = staticpath + savepath + "0" + i + ".pdf";  
                savepaths.add(savepath);  
            } else {  
                savepath = filepath.substring(  
                        filepath.lastIndexOf("\\") + 1,  
                        filepath.length() - 4);  
                savepath = staticpath + savepath + i + ".pdf";  
                savepaths.add(savepath);  
            }  
        }  
  
        for (int i = 0; i < N - 1; i++) {  
            document = new Document(reader.getPageSize(1));  
            copy = new PdfCopy(document, new FileOutputStream(  
                    savepaths.get(i)));  
            document.open();  
            for (int j = size * i + 1; j <= size * (i + 1); j++) {  
                document.newPage();  
                PdfImportedPage page = copy.getImportedPage(reader, j);  
                copy.addPage(page);  
            }  
            document.close();  
        }  
  
        document = new Document(reader.getPageSize(1));  
        copy = new PdfCopy(document, new FileOutputStream(  
                savepaths.get(N - 1)));  
        document.open();  
        for (int j = size * (N - 1) + 1; j <= n; j++) {  
            document.newPage();  
            PdfImportedPage page = copy.getImportedPage(reader, j);  
            copy.addPage(page);  
        }  
        document.close();  
  
    } catch (IOException e) {  
        e.printStackTrace();  
    } catch (DocumentException e) {  
        e.printStackTrace();  
    }  
}  

4.在Servlet中调用IText返回给客户端

a.将文件流直接返回给客户端

Java代码    

@Override  
protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
        throws ServletException, IOException {  
    resp.setContentType("application/pdf");  
    ServletOutputStream sos = resp.getOutputStream();  
    FileInputStream in = new FileInputStream("f:/fillTemplate.pdf");  
    byte data[] = new byte[1024];  
  
    int len = 0;  
    while ((len = in.read(data)) != -1) {  
        sos.write(data, 0, len);  
    }  
    sos.flush();  
    in.close();  
    sos.close();  
}

b.填充模版文件后将输出流返回给客户端

Java代码  

@Override  
protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
        throws ServletException, IOException {  
    resp.setContentType("application/pdf");  
  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    PdfReader reader = null;  
    PdfStamper ps = null;  
    try {  
        reader = new PdfReader(""); // 模版文件目录  
        ps = new PdfStamper(reader, baos);  
        AcroFields s = ps.getAcroFields();  
        s.setField("CUSTOMERNAME", "as该多好公司");  
        s.setField("TEL", "123456asdzxc");  
        s.setField("CONTACT", "我是联系人123");  
  
        ps.setFormFlattening(true); // 这句不能少  
        ps.close();  
        reader.close();  
    } catch (DocumentException e) {  
        e.printStackTrace();  
    }  
    ServletOutputStream sos = resp.getOutputStream();  
    baos.writeTo(sos);  
    sos.flush();  
    sos.close();  
}  

 

    上面转载自:点击打开链接

上面是转自别的博主,主要是itext对pdf的基本操作,下面主要说自己工作中遇到的问题: 怎么动态选中选框:

编辑工具:adobe

1 在itext 中的指定位置插入单选框或者复选框

2 双击选项框,然后点击:选框->导出值(填写成:true)

3 想让其选中,直接在Java中给对应的名称赋值为:true 则可以了。

     

### 使用 iTextPDF动态生成 PDF 列表 以下是基于 JavaiTextPDF 的实现方法,用于动态生成并填充 PDF 文件中的列表。此过程涉及创建文档、添加段落以及构建有序或无序列表。 #### Maven 依赖配置 在项目中引入必要的 iTextPDF 依赖项[^5]: ```xml <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> ``` #### 示例代码:动态生成 PDF 列表 以下是一个完整的示例代码,展示如何使用 iTextPDF 创建带有列表PDF 文档: ```java import com.itextpdf.text.Document; import com.itextpdf.text.List; import com.itextpdf.text.ListItem; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileOutputStream; public class PdfListExample { public static void main(String[] args) { Document document = null; try { // 初始化文档对象 document = new Document(); // 设置输出路径 String outputPath = "/Users/example/output_with_list.pdf"; PdfWriter.getInstance(document, new FileOutputStream(outputPath)); // 打开文档以便写入内容 document.open(); // 添加标题段落 Paragraph title = new Paragraph("Dynamic List Example"); document.add(title); // 创建一个无序列表 (bullet list) List unorderedList = new List(List.UNORDERED); unorderedList.setIndentationLeft(20); // 设置缩进 // 向无序列表中添加条目 unorderedList.add(new ListItem("First item")); unorderedList.add(new ListItem("Second item with more details")); unorderedList.add(new ListItem("Third item")); // 将无序列表添加到文档中 document.add(unorderedList); // 创建一个有序列表 (numbered list) List orderedList = new List(List.ORDERED); orderedList.setIndentationLeft(20); // 设置缩进 // 向有序列表中添加条目 orderedList.add(new ListItem("Step one")); orderedList.add(new ListItem("Step two")); orderedList.add(new ListItem("Final step")); // 将有序列表添加到文档中 document.add(orderedList); } catch (Exception e) { e.printStackTrace(); } finally { if (document != null && document.isOpen()) { document.close(); // 关闭文档 } } } } ``` 上述代码展示了如何通过 `List` 类型的对象分别创建 **无序列表** 和 **有序列表** 并将其嵌套至 PDF 文档中[^4]。 #### 输出说明 运行以上程序后,将在指定路径下生成名为 `output_with_list.pdf` 的文件。该文件包含两个部分: 1. 一段标题文字:“Dynamic List Example”。 2. 两组列表——一组为带圆点标记的无序列表;另一组为编号形式的有序列表。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值