![](/img/trans.png)
[英]How to save generated PDF files to MySQL database using Java?
[英]How to save generated PDF files to MySQL db using spring boot?
我有一個使用 iText 庫生成 PDF 文件的功能。 我的想法是將文檔轉換為字節數組,但我總是收到一個錯誤: com.itextpdf.text.Document@2805d0d4. The file cannot be found
com.itextpdf.text.Document@2805d0d4. The file cannot be found
。
這是我的 PDF 生成功能:
@Override
public Boolean createdPDF() throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextHelloWorld.pdf"));
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk("Hello World", font);
document.add(chunk);
document.close();
getByteArrayFromFile(document);
return true;
}
這是我從文件函數轉換字節數組:
private byte[] getByteArrayFromFile(Document handledDocument) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = new FileInputStream(String.valueOf(handledDocument));
byte[] buffer = new byte[500];
int read = -1;
while ((read = in.read(buffer)) > 0) {
baos.write(buffer, 0, read);
}
in.close();
Ticket newTicket = new Ticket();
newTicket.setFileName("example");
newTicket.setData(baos.toByteArray());
ticketRepository.save(newTicket);
return baos.toByteArray();
}
票務實體:
@Data
@Entity
public class Ticket {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String fileName;
@Lob
private byte[] data;
@NotNull
@JsonIgnore
@Column(updatable = false)
private LocalDateTime createAt;
@NotNull
@JsonIgnore
private LocalDateTime updatedAt;
}
以下是如何從 PdfDocument 獲取 byte[] 的示例:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Documentdocument = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk("Hello World", font);
document.add(chunk);
document.close();
pdfWriter.flush();
byte[] pdfAsBytes = baos.toByteArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.