实现pdf导出,前端是vue写的,我做的是java后端代码,参考的别人代码,调用wkhtmltopdf生成pdf,其中htmltopdf的工具类需要传入的参数为html字节码,我后端怎么获取前端vue界面的html字节码
@SneakyThrows(Exception.class)
public static byte[] htmlBytes2PdfBytes(byte[] htmlBytes) {
Document document = new Document(new ByteArrayInputStream(htmlBytes));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
document.save(outputStream, SaveFormat.PDF);
// 返回生成的`pdf`字节码
return outputStream.toByteArray();
}
java后端可以获取到vue页面的html字节码
题主,可以尝试一下,让Vue前端在调用后端接口的时候直接传入当前需要转换成PDF的Vue的HTML代码,然后通过POST请求的方式传到后端,然后将字符串转换成byte[] 。直接生成对应的PDF的文件,前端点击下载之后,直接将生成的文件路径告诉前端。这样可以解决您所说的问题。
还有另外的方式就是Vue支持将当前页面转换成PDF的操作具体的操作可以参考一下element-ui-admin
https://panjiachen.github.io/vue-element-admin-site/zh/ 这个里面的代码的写法
说白了你就是想后端获得文件流,如下
假设你的pdf文件是hello.pdf:
@Override
public void doSignStrData(Param param, HttpServletResponse response) throws IOException {
// C:/desktop/hello.pdf
String fileSignAddress = "C:/desktop/hello.pdf";
//如果存在,则转换
result(fileSignAddress,response);
}
private void result(String pdfPath, HttpServletResponse response) throws IOException {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline;fileName=" + pdfPath + ";fileName*=UTF-8''" + pdfPath);
//response.setHeader("Content-Disposition", "attachment; filename=\"" + pdfPath + "\"");
FileInputStream in;
OutputStream out;
try {
in = new FileInputStream(new File(pdfPath));
out = response.getOutputStream();
byte[] b = new byte[512];
while ((in.read(b)) != -1) {
out.write(b);
out.flush();
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!