자바 pdf 에 워 터 마크 추가
9908 단어 파일 다운로드
org.apache.pdfbox
pdfbox
2.0.13
com.itextpdf
itext-asian
5.2.0
com.itextpdf
itextpdf
5.5.9
2. 도구 종류:
package com.foresealife.lams.common.util;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
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.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;
import java.io.*;
public class PdfWatermarkUtil {
File file = new File("D:\\contractRelationTemplate\\test.pdf");
// .pdfbox ,, ,,。。。
public OutputStream test() throws IOException{
//
try (PDDocument doc = PDDocument.load(file)) {
int count = doc.getNumberOfPages();
for (int i = 0; i < count; i++) {
PDPage page = doc.getPage(i);
PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND,
true, true);
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
r0.setNonStrokingAlphaConstant(0.2f);
r0.setAlphaSourceFlag(true);
cs.setGraphicsStateParameters(r0);
cs.setNonStrokingColor(200, 0, 0);
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
cs.beginText();
cs.setFont(PDType1Font.HELVETICA_OBLIQUE, 33);
cs.setTextMatrix(Matrix.getRotateInstance(-50, 230 * m + (float) 60, 270 * n + (float) 100));
cs.showText("USE R");
cs.endText();
}
}
cs.close();
}
OutputStream os = new ByteArrayOutputStream();
doc.save(os);
return os;
//doc.save("D:\\software\\tyest1.pdf");
}
}
/**
* itextpdf ,
*
* @param bos
* @param input PDF
* @param word
* @param model 1 ,2
*/
public static void setWatermark(ByteArrayOutputStream bos, InputStream input, String word, int model) {
PdfReader reader = null;
try {
reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
PdfContentByte content;
// , ,itext :1
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//2 BaseFont base = BaseFont.createFont("/msyh.ttf", BaseFont.IDENTITY_H,
// BaseFont.EMBEDDED);
// linux , , windows , 。
// , 2,3 , resources 。
// 3
// BaseFont base = BaseFont.createFont("/simhei.ttf", BaseFont.IDENTITY_H,
// BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
// PDF
int total = reader.getNumberOfPages();
//
for (int i = 0; i < total; i++) {
//
float width = reader.getPageSize(i + 1).getWidth();
//
float height = reader.getPageSize(i + 1).getHeight();
//
content = stamper.getOverContent(i + 1);
//
content.beginText();
//
gs.setFillOpacity(0.2f);
content.setGState(gs);
content.setColorFill(BaseColor.RED);
//
content.setTextMatrix(70, 200);
if (model == 1) {
// 3
//
content.setFontAndSize(base, 50);
//showTextAligned ( , , X ,Y , )
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 650, 30);
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 400, 30);
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 150, 30);
} else {
// 4
//
float rotation = 30;
content.setFontAndSize(base, 20);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height - 50, rotation);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 4 * 3 - 50, rotation);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 2 - 50, rotation);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 4 - 50, rotation);
content.setFontAndSize(base, 22);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height - 50, rotation);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 4 * 3 - 50, rotation);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 2 - 50, rotation);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 4 - 50, rotation);
}
//
content.endText();
//
//Image image = Image.getInstance("c:/1.jpg");
//content.addImage(image);
}
stamper.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
3. Controller 층 사용 도구 류
// pdfbox
@RequestMapping("/api/test")
public void test(HttpServletRequest request, HttpServletResponse response) throws IOException{
PdfWatermarkUtil pdfWatermarkUtil = new PdfWatermarkUtil();
ByteArrayOutputStream out = (ByteArrayOutputStream)pdfWatermarkUtil.test();
ByteArrayInputStream inStream = new ByteArrayInputStream(out.toByteArray());
RequestUtils.testSupport(request,response,"fileName.pdf");
byte[] b = new byte[2048];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// response.getOutputStream().write(out.toByteArray());
}
// itextpdf ,
@RequestMapping("/api/getWaterMarkt")
public void getWaterMarkt(@RequestParam("id") long id, HttpServletRequest request, HttpServletResponse response) throws IOException{
String path = "E/fileName.pdf";
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWatermarkUtil.setWatermark(out, inputStream, " ", 1);
RequestUtils.downloadSupport(request,response,"fileName.pdf");
response.getOutputStream().write(out.toByteArray());
out.close();
}
====================================================================================================================================================================================================================================================================================
public static void testSupport(HttpServletRequest request, HttpServletResponse response, String formFileName) throws IOException {
String userAgent = request.getHeader("User-Agent");
if (userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident"))) {
// IE IE :
formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
} else {
// IE :
formFileName = new String(formFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", formFileName));
response.setCharacterEncoding("UTF-8");
}
//
public static void intSupport(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
ServletOutputStream os = null;
BufferedOutputStream out = null;
byte[] b = new byte[1024];
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
long pos = headerSetting(request, response, file);
os = response.getOutputStream();
out = new BufferedOutputStream(os);
raf.seek(pos);
int n = 0;
while ((n = raf.read(b, 0, 1024)) != -1) {
out.write(b, 0, n);
}
out.flush();
}
관련 글 참고:https://www.cnblogs.com/woshuaile/p/11943874.html
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 파일 다운로드의 몇 가지 실현 방식을 상세히 설명하다Java 파일을 다운로드하는 방법은 다음과 같습니다. //파일을 온라인으로 열 수 있는 방법 이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.