生成PDF/XLSX文件作为REST API附件是指在后端服务中动态创建PDF或Excel文件,然后通过HTTP响应将这些文件作为附件返回给客户端的技术。这种技术常用于报表导出、数据下载等场景。
@RestController
public class PdfController {
@GetMapping("/generate-pdf")
public ResponseEntity<byte[]> generatePdf() throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
document.add(new Paragraph("Hello, this is a PDF generated by REST API"));
document.close();
byte[] bytes = outputStream.toByteArray();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"example.pdf\"")
.contentType(MediaType.APPLICATION_PDF)
.body(bytes);
}
}
const express = require('express');
const PDFDocument = require('pdfkit');
const app = express();
app.get('/generate-pdf', (req, res) => {
const doc = new PDFDocument();
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename="example.pdf"');
doc.pipe(res);
doc.fontSize(25).text('Hello from PDFKit!', 100, 100);
doc.end();
});
app.listen(3000);
@RestController
public class ExcelController {
@GetMapping("/generate-excel")
public ResponseEntity<byte[]> generateExcel() throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue(1);
dataRow.createCell(1).setCellValue("Example");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
workbook.close();
byte[] bytes = outputStream.toByteArray();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"example.xlsx\"")
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
}
const express = require('express');
const ExcelJS = require('exceljs');
const app = express();
app.get('/generate-excel', async (req, res) => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet1');
worksheet.columns = [
{ header: 'ID', key: 'id' },
{ header: 'Name', key: 'name' }
];
worksheet.addRow({ id: 1, name: 'Example' });
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename="example.xlsx"');
await workbook.xlsx.write(res);
res.end();
});
app.listen(3000);
问题:生成大文件时可能导致内存溢出
解决方案:
问题:生成复杂文件耗时过长
解决方案:
问题:某些客户端无法正确打开生成的文件
解决方案:
问题:中文内容显示为乱码
解决方案:
通过以上方法和实践,可以高效、安全地实现PDF/XLSX文件作为REST API附件的功能。
没有搜到相关的文章