page contents

itext 生成PDF后不知道该怎么设置输出流返回给前端!!

Pack 发布于 2020-01-03 15:31
阅读 918
收藏 0
分类:WEB前端开发

问题描述

我使用itext生成PDF文件之后,无论怎么设置输出流信息,前端都不能正常解析,还请有相关经验的前辈们,不吝赐教!!!


问题出现的环境背景及自己尝试过哪些方法

尝试过建单粗暴的方式:

Document document = new Document(PageSize.A4);

PdfWriter writer;

OutputStream out = response.getOutputStream();

response.setCharacterEncoding(“UTF-8”);

response.setHeader(“content-Type”, “application/pdf”);

response.setHeader(“Content-Disposition”, “inline;filename=” + URLEncoder.encode(“test.pdf”, “UTF-8”));

writer = PdfWriter.getInstance(document, out); out.flush();

out.close();

document.close();

writer.close();


也尝试过细节处理:

String result = new String(baos.toByteArray(), StandardCharsets.ISO_8859_1);//转字符串设置编码

result = java.net.URLEncoder.encode(result, “ISO-8859-1”);//如果跨域需设置编码

ByteArrayInputStream inStream = new ByteArrayInputStream(result.getBytes(“ISO-8859-1”));

// 设置输出的格式

response.setContentType(“bin”);

response.addHeader(“Content-Disposition”, “attachment; filename=downLoad.PDF”);

// 循环取出流中的数据

byte[] b = new byte[2048];

int len;

while ((len = inStream.read(b)) > 0)

response.getOutputStream().write(b, 0, len);

inStream.close();


相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)


你期待的结果是什么?实际看到的错误信息又是什么?

希望大佬们能同时贴出java代码和前端代码,临表涕零~

94
Pack
Pack

ByteArrayOutputStream output = new ByteArrayOutputStream();

ITextRenderer render = new ITextRenderer();

ITextFontResolver fontResolver = render.getFontResolver();

fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

render.setDocumentFromString(htmlContent);

render.getSharedContext().setBaseURL(BASE_URL);

render.layout();

render.createPDF(output);

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

headers.setContentDispositionFormData(“attachment”, fileName);

return new ResponseEntity(fileBytes, headers, HttpStatus.OK);

请先 登录 后评论