依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
Controller
@GetMapping("/QRPdf")
public void getPdf(HttpServletResponse response,String[] batchNos) throws Exception{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
List<CodeList> codeLists=identityCodeInstanceService.getQRForPDF(Arrays.asList(batchNos));
QRCodeEntity qrCodeEntity = new QRCodeEntity(
out, 300, 300, 10, 0, codeLists);
new Thread(
() -> {
try {
QRCodeToPDF qrCodeToPDF = new QRCodeToPDF();
qrCodeToPDF.createPDF(qrCodeEntity);
out.close();
} catch (IOException | DocumentException e) {
throw new RuntimeException(e);
}
}
).start();
response.setContentType("application/pdf;charset-UTF-8");
ServletOutputStream resOut = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = in.read(buffer)) != -1) {
resOut.write(buffer, 0, len);
}
resOut.flush();
实体
import lombok.Data;
@Data
public class CodeList {
private String codeScan;
private String codeTitle;
}
package com.yc.asset.mgt.admin.common.utils.file.print;
import lombok.Data;
import java.io.PipedOutputStream;
import java.util.List;
@Data
public class QRCodeEntity {
private PipedOutputStream fileOutputStream;
private int codeWidth;
private int codeHeight;
private int absoluteX;
private int absoluteY;
private List<CodeList> codelist;
public QRCodeEntity(PipedOutputStream fileOutputStream, int codeWidth, int codeHeight, int absoluteX, int absoluteY, List<CodeList> codelist) {
this.fileOutputStream = fileOutputStream;
this.codeWidth = codeWidth;
this.codeHeight = codeHeight;
this.absoluteX = absoluteX;
this.absoluteY = absoluteY;
this.codelist = codelist;
}
}
将生成Document 写入输出流
public void createPDF(QRCodeEntity qrCodeEntity) throws DocumentException
{
Document document = new Document(new Rectangle(300f,300f),30,30,10,30);
PdfWriter.getInstance(document,qrCodeEntity.getFileOutputStream());
document.open();
int size = qrCodeEntity.getCodelist().size();
for (int i = 0; i < size; i++)
{
document.newPage();
BarcodeQRCode qrcode = new BarcodeQRCode(qrCodeEntity.getCodelist().get(i).getCodeScan(),
qrCodeEntity.getCodeWidth(),
qrCodeEntity.getCodeHeight(),
null);
Image qrcodeImage = qrcode.getImage();
qrcodeImage.setAbsolutePosition(qrCodeEntity.getAbsoluteX(),qrCodeEntity.getAbsoluteY());
document.add(qrcodeImage);
Paragraph elements = new Paragraph(qrCodeEntity.getCodelist().get(i).getCodeTitle());
document.add(elements);
}
document.close();
}