我是java新手,现在我尝试使用itextpdf库,代码是:与mysql建立连接,运行查询并获取一个字节对象,现在我需要将这些字节放在mi上的页面上pdf 文档。 我的数据库中的数据是字节格式的pdf文件,mysql数据类型是“long blob”
现在我认为需要一些类似的代码
byte[] bytes = null;
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("\some\dir\file.pdf"));
document.open();
Class.forName("com.mysql.jdbc.Driver");
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "user", "pass");
PreparedStatement st = cn.prepareStatement("SELECT file FROM files");
ResultSet rs = st.executeQuery();
try {
while (rs.next()) {
bytes = rs.getBytes("file");
document.add(bytes);
document.close();
cn.close();
} catch (Exception e) {
System.out.println(e);
}
}
最佳答案
如果字节
包含需要在PDF内呈现的文本,则需要替换以下行:
document.add(bytes);
使用以下行:
document.add(new Paragraph(new String(bytes)));
如果bytes
包含特殊字符,您可能会遇到编码问题,但让我们一步一步解决这个问题。
如果字节
是完整且有效的PDF文件,您需要将它们提供给PdfReader
对象:
PdfReader reader = new PdfReader(bytes);
接下来发生的事情完全取决于您想要对 PDF 文件执行的操作。如果您只需要提供 PDF,那么显然您根本不需要 iText。如果您想复制特定页面或将该文件与其他文件合并,则需要使用 PdfCopy
。如果您想在文件上标记额外的数据(水印、页码等),您需要 PdfStamper
。阅读 Chapter 6阅读我的书来了解您可以做什么,并查看表 6.1 以确保您选择了正确的类别。
更好的主意是使用 iText 7 而不是 iText 5。在这种情况下,您需要阅读章节 Manipulating an existing PDF document和 Reusing existing PDF documents iText 7 快速入门教程。
关于java - 来自 mysql 连接的 itextpdf pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40990297/