使用Java中的iText生成PDF base64编码

时间:2017-10-27 00:35:50

标签: java base64 itext

如何将iText中生成的PDF文件编码为base64?

这是我的(java)代码

App.java

public class App {

public static void main(String[] args) throws DocumentException, IOException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));
    // step 3
    document.open();

    String str = "<html><head></head><body style=\"font-size:12.0pt; font-family:Times New Roman\">"
            + "<a href='http://www.rgagnon.com/howto.html'><b>Real's HowTo</b></a>" + "<h1>Show your support</h1>"
            + "<p>It DOES cost a lot to produce this site - in ISP storage and transfer fees</p>"
            + "<p>TEST POLSKICH ZNAKÓW: \u0104\u0105\u0106\u0107\u00d3\u00f3\u0141\u0142\u0179\u017a\u017b\u017c\u017d\u017e\u0118\u0119</p>"
            + "<hr/>"
            + "<p>the huge amounts of time it takes for one person to design and write the actual content.</p>"
            + "<p>If you feel that effort has been useful to you, perhaps you will consider giving something back?</p>"
            + "<p>Donate using PayPal\u017d</p>" + "<p>Contributions via PayPal are accepted in any amount</p>"
            + "<p><br/><table border='1'><tr><td>Java HowTo</td></tr><tr>"
            + "<td style='background-color:red;'>Javascript HowTo</td></tr>"
            + "<tr><td>Powerbuilder HowTo</td></tr></table></p>" + "</body></html>";

    XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
    InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));

    worker.parseXHtml(writer, document, is, Charset.forName("UTF-8"));

    // step 5
    document.close();

    System.out.println("PDF Created!");

}

}

iText库依赖项(xmlworker e itextpdf)

Pom文件:

    <dependencies>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.2</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.4.1</version>
    </dependency>
</dependencies>

我卡住了,欢迎任何帮助。

2 个答案:

答案 0 :(得分:0)

我必须做同样的事情,这就是我做到的。我使用apache.commons库来编码并将文件内容读入字节数组。希望这会有所帮助。

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

File file = new File("test.pdf");

  // write your html template to the file and close the document.
byte[] pdf =FileUtils.readFileToByteArray(file);
byte[] encoded = Base64.encodeBase64(pdf); 
      //or byte[] encoded = Base64.encodeBase64(file.getBytes());

这是在groovy中完成的,根据您的要求编写适当的代码。

答案 1 :(得分:0)

使用标准java.util.Base64:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);

byte[] bytes = baos.toByteArray();
bytes = Base64.getEncoder().encode(bytes);
Files.write(Paths.get("pdf.pdf"), bytes);