package com.ruoyi.web.controller.system;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
public class PdfUtils {
public static void insertTextAtPosition(String filePath, int pageNumber, float x, float y,
String text,String fileOutPath){
try {
PDDocument document = PDDocument.load(new File(filePath));
PDPage page = document.getPage(pageNumber - 1);
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
contentStream.setFont(PDType1Font.HELVETICA, 12);
contentStream.beginText();
contentStream.newLineAtOffset(x, y);
contentStream.showText(text);
contentStream.endText();
contentStream.close();
document.save(new File(fileOutPath));
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void insertImage(String filePath, String imagePath, int pageNumber, float x, float y, float width, float height,
String fileOutPath, HttpServletResponse response) throws IOException {
ServletOutputStream out=null;
try {
PDDocument document = PDDocument.load(new File(filePath));
PDPage page = document.getPage(pageNumber - 1);
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, document);
contentStream.drawImage(pdImage, x, y, width, height);
contentStream.close();
document.save(new File(fileOutPath));
response.setContentType("application/pdf");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + new File(fileOutPath).getName());
out = response.getOutputStream();
document.save(out);
document.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out!=null){
out.close();
}
}
}
}
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>