我想在将 PDF 发送到 FileOutputStream
之前以 Base64 格式存储它。我尝试了下面的代码。我尝试将 OutputStream
的 write
方法与匿名内部类一起使用,但内容为 null。
package com.hmkcode;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.html2pdf.HtmlConverter;
public class App
{
public static final String HTML = "<h1>Hello</h1>"
+ "<p>This was created using iText</p>"
+ "<a href='hmkcode.com'>hmkcode.com</a>";
public static void main( String[] args ) throws FileNotFoundException, IOException {
HtmlConverter.convertToPdf(HTML, new FileOutputStream("string-to-pdf.pdf"));
System.out.println( "PDF Created!" );
}
}
最佳答案
您可以简单地使用java.util.Base64.Encoder
类的wrap
方法来获取执行Base64编码的OutputStream
写入任何内容:
FileOutputStream fos = new FileOutputStream("pdf-base64.txt");
OutputStream base64os = Base64.getEncoder().wrap(fos);
HtmlConverter.convertToPdf(HTML, base64os);
请注意,文档说要关闭 Base64 输出流:
It is recommended to promptly close the returned output stream after use, during which it will flush all possible leftover bytes to the underlying output stream. Closing the returned output stream will close the underlying output stream.
convertToPdf
自动关闭输出流,但如果您以不同方式创建 PDF,请确保调用 base64os.close()
。
如果由于某种原因您想先创建 PDF,然后再进行 Base64 编码,您可以使用众多 Base64 编码实现之一。例如,使用java.util.Base64.Encoder
:
// Create PDF
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HtmlConverter.convertToPdf(HTML, baos);
// Generate Base64 encoded version of PDF
byte[] base64encoded = Base64.getEncoder().encode(baos.toByteArray());
// Write Base64 data to file
FileOutputStream fos = new FileOutputStream("pdf-base64.txt");
fos.write(base64encoded);
fos.close();
关于java - 如何以字符串 Base64 格式存储 PDF 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59803467/