itext pdf写入可见附件

itext处理pdf文件非常灵活,现在把写入在adobe reader中打开pdf文件后在左侧附件栏中可以看到的附件:
   public byte[] addAttachmentForItext(byte[] pdf, Map<String, byte[]> attachMap) throws IOException,
            DocumentException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(pdf);
        PdfStamper stamper = null;
        try {
            stamper = new PdfStamper(reader, byteOut);
            // PdfFileSpecification pfs =
            // PdfFileSpecification.fileEmbedded(stamper.getWriter(),
            // "C:\\Users\\chentao\\Desktop\\filetrace.XML", "test", null);
            // stamper.addFileAttachment(null, pfs);
            for (Entry<String, byte[]> attach : attachMap.entrySet()) {
                //方法参数依次为:附件描述,附件流,附件文件(流和文件传一个就可以),附件名称
                stamper.addFileAttachment(attach.getKey(), attach.getValue(), null, attach.getKey());
            }
        } 
        return byteOut.toByteArray();
    }
当然,可以写可见附件,肯定可以写隐藏的文件,就是往pdf里面藏东西。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是使用itextpdf类在pdf指定位置写入字符串的示例代码: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import java.io.FileOutputStream; import java.io.IOException; public class PdfWriterExample { public static void main(String[] args) { try { // 读取原始PDF文件 PdfReader reader = new PdfReader("input.pdf"); // 创建输出PDF文件 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf")); // 获取指定页面的内容流 PdfContentByte content = stamper.getOverContent(1); // 设置字体 BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font = new Font(baseFont, 12, Font.NORMAL); // 在指定位置添加文本 content.beginText(); content.setFontAndSize(baseFont, 12); content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Hello, World!", 100, 100, 0); content.endText(); // 关闭PDF文件 stamper.close(); reader.close(); } catch (IOException | DocumentException e) { e.printStackTrace(); } } } ``` 这段代码使用itextpdf库来读取原始的PDF文件,并在指定位置添加文本。首先,我们创建一个PdfReader对象来读取原始PDF文件。然后,我们创建一个PdfStamper对象来写入输出PDF文件。通过调用`getOverContent()`方法,我们可以获取指定页面的内容流。接下来,我们设置字体并使用`showTextAligned()`方法在指定位置添加文本。最后,我们关闭PDF文件。 请注意,这只是一个示例代码,你需要根据你的实际需求进行适当的修改。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值