gpt4 book ai didi

java - 如何使用 Spring Boot 将生成的 PDF 文件保存到 MySQL 数据库?

转载 作者:行者123 更新时间:2023-12-02 00:59:40 27 4
gpt4 key购买 nike

我有一个使用 iText 库生成 PDF 文件的函数。我的想法是将文档转换为字节数组,但我总是收到错误:com.itextpdf.text.Document@2805d0d4。找不到该文件

这是我的 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();

关于java - 如何使用 Spring Boot 将生成的 PDF 文件保存到 MySQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60850346/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com