主要代码如下,如需运行,请将recordsResult.getFileUrl()替换成ssjson文件url,recordsResult.getExtendDataJson()替换成datasource
/**
* 生成PDF文件的展示效果
*
* @param records
* @param response
* @return
*/
@ApiOperation(value = "生成PDF文件的展示效果", notes = "生成PDF文件的展示效果")
@PostMapping(value = "/testOriginalRecordsPdfView")
public void testOriginalRecordsPdfView(@RequestBody SampleTaskOriginalRecords records, HttpServletResponse response) throws Exception {
SampleTaskOriginalRecords recordsResult = iSampleTaskOriginalRecordsService.getById(records.getId()).getResult();
//获取ssjson文件并载入GCExcel
InputStream inputStream = PoiTlUtil.urlToInputStream(preUrlPath + recordsResult.getFileUrl());
Workbook workbook = new Workbook();
workbook.fromJson(inputStream);
Map<String, Object> sheetDataMap = JSONObject.parseObject(recordsResult.getExtendDataJson(), new TypeReference<Map<String, Object>>(){});
//迭代每个sheet页,设置显示方向和显示百分比
for (int i = 0; i < workbook.getWorksheets().getCount(); i++) {
IWorksheet sheet = workbook.getWorksheets().get(i);
// sheet.getPageSetup().setCenterHorizontally(true);
sheet.getPageSetup().setBlackAndWhite(true);
if ("设备".equals(sheet.getName()) || "参数".equals(sheet.getName()) || sheet.getName().startsWith("基本信息")) {
sheet.setVisible(Visibility.VeryHidden);
}
if (sheetDataMap.containsKey(sheet.getName())) {
sheet.setDataSource(new JsonDataSource(JSONObject.toJSONString(sheetDataMap.get(sheet.getName()))));
}
}
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String newName = sd.format(new Date()) + ".pdf";
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/pdf;charset=utf-8");
response.setHeader("Access-Control-Expose-Headers","Content-disposition");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(newName, "UTF-8"));
workbook.save(outputStream, SaveFileFormat.Pdf);
//关闭流
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} |