pdf 파일 과 이미지 파일 워 터 마크 에 자바 방법 및 jar 패키지 추가
11613 단어 자바
현재 수준 이 제한 되 어 있 는 지 pdf 파일 을 추가 할 때 pdf 파일 을 그림 형식 으로 바 꾼 다음 에 진행 하 는 워 터 마크 를 추가 한 다음 에 pdf 형식 문 서 를 되 돌려 줍 니 다.다음은 코드.
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.util.GraphicsRenderingHints;
import com.eos.system.annotation.Bizlet;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.mln.frame.CompressFile;
import com.mln.wateroa.files.filesdataset.AtFileupload;
import commonj.sdo.DataObject;
import org.gocom.components.coframe.tools.CoframeDASDaoSupport;
/**
* @author admin
* @date 2018-08-13 16:03:30
*
*/
public class PdfWaterMarkUtil extends CoframeDASDaoSupport{
String uuid = UUID.randomUUID().toString().replace("-", "");
//
public static void main(String[] args) throws PDFException, PDFSecurityException, IOException, InterruptedException {
PdfWaterMarkUtil pwm = new PdfWaterMarkUtil();
ArrayList imageUrllist = new ArrayList();
String logoText = " TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST";
String srcImgPath = "G:\\22-1xxxxxxx.pdf";
pwm.waterMark(srcImgPath, logoText);
}
/**
* pdf
* @param srcImgPath
* @param logoText
* @return pdf
* @throws InterruptedException
* @throws IOException
* @throws PDFSecurityException
* @throws PDFException
*/
public String PdfWaterMarks (String srcImgPath,String logoText) throws PDFException, PDFSecurityException, IOException, InterruptedException{
PdfWaterMarkUtil pwm = new PdfWaterMarkUtil();
ArrayList imageUrllist = new ArrayList();
String pngpath = pwm.pdfToPic(srcImgPath);//pdf
String targerTextPath = pwm.markImageByText(logoText, pngpath, -20);//
imageUrllist.add(targerTextPath);
String newPdfPath = srcImgPath.substring(0,srcImgPath.lastIndexOf("."))+uuid;
String newPdfUrl = newPdfPath+"new.pdf";
File file = pwm.PngToPdf(imageUrllist, newPdfUrl); // pdf
pwm.deleteFile(pngpath);
pwm.deleteFile(targerTextPath);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newPdfUrl;
}
/**
*
* @param srcImgPath
* @param logoText
* @return
*/
public String JpgWaterMarks(String srcImgPath,String logoText){
String targerTextPath = markImageByText(logoText, srcImgPath, -20);//
return targerTextPath;
}
/**
* pdf
* @param srcImgPath
* @param logoText
* @return
*/
public String waterMark(String srcImgPath,String logoText) throws PDFException, PDFSecurityException, IOException, InterruptedException{
String imgType = srcImgPath.substring(srcImgPath.lastIndexOf(".")+ 1).toLowerCase();
PdfWaterMarkUtil pwm = new PdfWaterMarkUtil();
String newPath = null;
System.out.println(imgType);
if (imgType.contains("pdf")){// pdf
System.out.println("pdf ");
newPath = PdfWaterMarks(srcImgPath,logoText);
}else
if(imgType.contains("bmp")||imgType.contains("pcx")||imgType.contains("tiff")||imgType.contains("gif")||imgType.contains("jpeg")
||imgType.contains("tga")||imgType.contains("exif")||imgType.contains("fpx")||imgType.contains("svg")||imgType.contains("psd")
||imgType.contains("cdr")||imgType.contains("pcd")||imgType.contains("dxf")||imgType.contains("ufo")||imgType.contains("eps")
||imgType.contains("png")||imgType.contains("hdri")||imgType.contains("ai")||imgType.contains("raw")||imgType.contains("raw")
||imgType.contains("ico")||imgType.contains("webp")||imgType.contains("flic")||imgType.contains("emf")||imgType.contains("jpg")){//
System.out.println(" ");
newPath = pwm.JpgWaterMarks(srcImgPath, logoText);
}else{
newPath = srcImgPath;
}
return newPath;
}
/**
*
* @param srcImgPath
* @param logoText
* @return
*/
@Bizlet("")
public String PicWaterMark(String srcImgPath,String logoText){
PdfWaterMarkUtil a = new PdfWaterMarkUtil();
String targerTextPath = a.markImageByText(logoText, srcImgPath, -20);
return targerTextPath;
}
//
private static float alpha = 0.5f;
//
private static Color color = Color.gray;
/*
* pdf
*/
public String pdfToPic(String pdfPath) throws PDFException, PDFSecurityException, IOException, InterruptedException{
String newPath1 = pdfPath.substring(0,pdfPath.lastIndexOf("."))+uuid;
//String newPath2 = pdfPath.substring(pdfPath.lastIndexOf("."));
String newPath = newPath1+".png";
org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
document.setFile(pdfPath);
float scale = 2.5f;//
float rotation = 0f;//
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)
document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
// String imgName = i + ".png";
System.out.println(newPath);
File file = new File(newPath);
ImageIO.write(rendImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
}
document.dispose();
return newPath;
}
// pdf
public File PngToPdf(ArrayList imageUrllist,String mOutputPdfFileName) {
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter
.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
doc.open();
for (int i = 0; i < imageUrllist.size(); i++) {
//doc.newPage();
//doc.add(new Paragraph(" iText"));
Image png1 = Image.getInstance(imageUrllist.get(i));
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.scalePercent(percent+3);// ;
doc.add(png1);
}
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
System.out.println(" PDF ");
return mOutputPdfFile;
}
/**
* , , ,
*
* @param args
*/
public static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
/*
*
*/
public String markImageByText(String logoText, String srcImgPath, Integer degree) {
String newPath1 = srcImgPath.substring(0,srcImgPath.lastIndexOf("."));
String newPath2 = srcImgPath.substring(srcImgPath.lastIndexOf("."));
String targerPath = newPath1+"new" +newPath2;
System.out.println(targerPath);
InputStream is = null;
OutputStream os = null;
try {
// 1、
File file = new File(srcImgPath);
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (Exception e) {
e.printStackTrace();
}
int width = bi.getWidth(); //
int height = bi.getHeight(); //
java.awt.Image srcImg = ImageIO.read(file);
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
// 2、
Graphics2D g = buffImg.createGraphics();
// 3、
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(
srcImg.getScaledInstance(srcImg.getWidth(null),
srcImg.getHeight(null), java.awt.Image.SCALE_SMOOTH), 0, 0,
null);
// 4、
if (null != degree) {
g.rotate(Math.toRadians(degree),(double) buffImg.getWidth() / 2,(double) buffImg.getHeight()/ 2);
}
//
Font font = new Font(" ", Font.BOLD, width/30);
// 5、
g.setColor(color);
g.setFont(font);
// 7、
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
// 8、 -> , -> (x,y)
FontMetrics fm = g.getFontMetrics(font);
int textWidth = fm.stringWidth(logoText);
int widthX = (width - textWidth) / 2;
g.drawString(logoText, widthX, height/2); //
// 9、
g.dispose();
// 10、
os = new FileOutputStream(targerPath);
System.out.println(os);
ImageIO.write(buffImg, "JPG", os);
System.out.println(" ");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return targerPath;
}
}
관련 jar 패키지 다운로드 주소 첨부 관련 PDF 도구 jar 패키지 다운로드
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.