Java PDF添加附件

博客介绍了Free-Spire-PDF-API的地址,还提及了在pom.xml中进行maven依赖导入,给出了相关代码及效果展示,同时提供了GitHub代码仓库链接,主要围绕Java使用该API操作PDF展开。

Free-Spire-PDF-API地址: http://www.e-iceblue.cn/Introduce/Free-Spire-PDF-JAVA.html

pom.xml maven依赖导入

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.design.patterns</groupId>
    <artifactId>design-patterns</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>design-patterns</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-xtra</artifactId>
            <version>5.5.13</version>
        </dependency>

        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.pdf.free</artifactId>
            <version>2.2.2</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

代码

package com.design.patterns.designpatterns.pdf;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.annotations.*;
import com.spire.pdf.attachments.PdfAttachment;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class AttachFiles {

    static String src = "E:\\pdf\\qqq.pdf";     // 原文件
    static String dest = "E:\\pdf\\ccc.pdf";    // 最终文件
    static String att = "E:\\pdf\\666.mp4";     // 附件
    static String desc = "附件";                 // 附件注释

    public static void main(String[] args) throws IOException {

        //创建PdfDocument对象
        PdfDocument doc = new PdfDocument();

        //加载PDF文档
        doc.loadFromFile(src);

        //添加附件到PDF
        PdfAttachment attachment = new PdfAttachment(att);
        attachment.setDescription(desc);
        doc.getAttachments().add(attachment);

        int count = doc.getPages().getCount() - 1;

        //绘制标签
        String label = "视频.mp4";
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12),true);
        double x = 35;
        double y = doc.getPages().get(count).getActualSize().getHeight() - 800;
        doc.getPages().get(count).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);

        //添加注释附件到PDF
        String filePath = att;
        byte[] data = toByteArray(filePath);
        Dimension2D size = font.measureString(label);
        Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 2), (float) y, 10, 15);
        PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
        annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));
        annotation.setFlags(PdfAnnotationFlags.Default);
        annotation.setIcon(PdfAttachmentIcon.Graph);
        annotation.setText("双击打开文件");
        doc.getPages().get(0).getAnnotationsWidget().add(annotation);

        //保存文档
        doc.saveToFile(dest);
    }

    //读取文件到byte数组
    public static byte[] toByteArray(String filePath) throws IOException {

        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }

        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }
}

效果:

 

GitHup: https://github.com/liu911025/pdf-addAttachments/tree/master

使用 Java 根据字段生成 PDF 附件可以借助一些开源库来实现,下面介绍使用 iText 库的示例。iText 是一个广泛用于处理 PDFJava 库,能方便地根据字段信息生成 PDF 文件。 首先,在 Maven 项目中添加 iText 的依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.3</version> </dependency> ``` 以下是一个简单的 Java 代码示例,展示如何根据字段生成 PDF 附件: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class GeneratePDFWithFields { public static void main(String[] args) { // 创建一个 Document 对象 Document document = new Document(); try { // 创建一个 PdfWriter 实例,将文档写入指定的文件 PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); // 打开文档 document.open(); // 定义要添加PDF 中的字段信息 String field1 = "这是第一个字段的内容"; String field2 = "这是第二个字段的内容"; // 将字段信息作为段落添加到文档中 document.add(new Paragraph(field1)); document.add(new Paragraph(field2)); // 关闭文档 document.close(); System.out.println("PDF 文件生成成功!"); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } } } ``` 上述代码中,先创建了一个 `Document` 对象,接着使用 `PdfWriter` 将文档内容写入指定文件。然后定义了两个字段信息,并将它们作为段落添加到文档中,最后关闭文档完成 PDF 文件的生成。 如果要实现更复杂的 PDF 生成,比如根据模板生成,可参考引用[2]中的相关内容,结合具体的业务逻辑,在 Controller 层调用相应的服务方法来生成包含特定字段信息的 PDF 附件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值