gpt4 book ai didi

jquery - 使用 servlet 生成 PDF 文件并在新的浏览器选项卡中显示 PDF - PDF 文件为空

转载 作者:行者123 更新时间:2023-12-01 01:32:59 25 4
gpt4 key购买 nike

我有一个现有的 servlet,它为我提供了一个 pdf 字节数组:

byte[] pdf = myService.getPdf(myArgs);
response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, postcheck=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentLength(pdf.length);
ServletOutputStream out = response.getOutputStream();
out.write(pdf);
out.flush();
out.close();

// for test: byte[] pdf
File testfile = new File("C:\\mytestpath\\mytest.pdf");
FileOutputStream fos = new FileOutputStream(testfile);
fos.write(pdf);
fos.flush();
fos.close();

我在 servlet 中编写了一个测试 pdf 文件来检查 myService.getPdf() 的返回值。测试文件没问题,我可以在 acrobat reader 中打开这个有效文件。

现在我的 JQuery-JavaScript 代码:

function generatePDF(url) {
currentRequest = $.ajax({
url: url,
type: "GET",
success: function(data) {
var blob = new Blob([data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(blob);
window.open(fileURL, "_blank");
},
error: function() {
console.error("test in generatePDF error");
// use here other jquery mobile functions
}
});
}

我想在我的 servlet 中生成 PDF 字节数组并在新的浏览器选项卡中显示 PDF。在我的实现中,打开了一个新的 browsersr 选项卡(地址行:blob:http%3A//localhost%3A8080/3fd5808b-758b-4076-94c9-af9884f631a3)。但是PDF文件是空的,PDF文件的页面大小是可以的。我怎么解决这个问题?我需要在新的浏览器选项卡中提供名为 myid.pdf 的有效 PDF。

谢谢你的提示,托马斯

最佳答案

您可以在新窗口中打开您的 servlet URL。不需要 AJAX 调用或 JQuery。

在您的 servlet 中,您可以添加 header ,提示浏览器在用户选择保存文件时向用户建议什么文件名。

response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);

关于jquery - 使用 servlet 生成 PDF 文件并在新的浏览器选项卡中显示 PDF - PDF 文件为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298933/

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