如何在使用FlyingSaucer创建的PDF中设置metada

时间:2017-06-08 15:40:26

标签: java pdf itext metadata flying-saucer

我试图在我使用FlyingSaucer(https://github.com/flyingsaucerproject/flyingsaucer)从HTML文件创建的PDF文件中设置元数据(例如标题或作者)。

这是创建PDF文件的代码:

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.setDocumentFromString(... HTML as a String ...);
    renderer.layout();
    renderer.createPDF(out);

    FileOutputStream fos = new FileOutputStream(pathPdf);

    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, fos);

    ... sets watermark image if available ...

    stamper.close();
    reader.close();

我尝试过获取PdfDictionary并设置元数据,获取信息图并设置元数据,并获取文档来设置元数据,但我无法使其工作。

2 个答案:

答案 0 :(得分:2)

您可以更轻松地进行操作。实质是让作者成为createPdf方法之后的对象,并且在创建pdf时一定不要关闭文档,而必须在最后手动进行:

 ITextRenderer renderer = new ITextRenderer();
 renderer.setDocumentFromString(html); 
 renderer.layout();
 renderer.createPDF(outputStream, false);
 renderer.getWriter().getInfo().put(PdfName.CREATOR, new PdfString("witek"));
 renderer.finishPDF();

答案 1 :(得分:1)

找到解决方案:

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.setDocumentFromString(... HTML as a String ...);
    renderer.layout();
    renderer.createPDF(out);

    FileOutputStream fos = new FileOutputStream(pathPdf);

    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, fos);

    ... sets watermark image if available ...

    PdfDictionary info = reader.getTrailer().getAsDict(PdfName.INFO);
    info.getKeys().forEach((k) -> {
        System.out.println("k: " + k + ", v:" + info.get((PdfName) k));
    });
    info.put(PdfName.TITLE, new PdfString("Title", PdfObject.TEXT_UNICODE));
    info.put(PdfName.AUTHOR, new PdfString("Author", PdfObject.TEXT_UNICODE));

    stamper.close();
    reader.close();