pdf 워 터 마크, 텍스트, 그림, 하이퍼링크, 자바 itext, 여기 원 하 는 모든 것 이 있 습 니 다.
jar 패키지 주소:https://github.com/CrossRef/pdfstamp
쓸데없는 소리 하지 말고 코드 를 붙 이 고 유용 하 다 면 수 동 으로 좋아요 주 를 누 르 세 요: itext 가방 이 필요 합 니 다.
package org.crossref.pdfstamp;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
// -u "http://blah.com" -i somefile.jpeg -l 1,44.5,22.3,3,22.2,22.2 some/dir
// or some.file
// or:
//-u "http://blah.com" -i somefile.jpeg -l 1,44.5,22.3 -l 3,22.2,22.2 some/dir
// or some.file
public class Main {
//
@Option(name="-p", usage="Optional. Page numbers to stamp. -1 is the last page.",
required=false, multiValued=true, metaVar="P1,P2...")
private List pages = new ArrayList();
@Option(name="-l", usage="Required. Location on page to apply stamp.",
required=true, multiValued=false, metaVar="X,Y")
private StampTuple stampLocation = new StampTuple();
@Option(name="-e", usage="Optional. Extension appended to the PDF filename.",
required=false, multiValued=true, metaVar="EXT")
private String outputExtension = "stamped";
@Option(name="-r", usage="Optional. Descend recursively into directories.")
private boolean recursive = false;
@Option(name="-u", usage="Optional. Target URL of the stamp.",
required=false, multiValued=false, metaVar="URL")
private String url = "";
@Option(name="-b", usage="Optional. Brand for stamp.",
required=false, multiValued=false, metaVar="BRAND")
private String brand = "";
@Option(name="-i", usage="Required. Image file containing image of the stamp.",
required=true, multiValued=false)
private File imageFile = new File(".");
@Option(name="-o", usage="Optional. Output directory.",
required=false, multiValued=false)
private File outputDirectory = null;
@Option(name="-v", usage="Optional. Verbose output.",
required=false, multiValued=false)
private boolean verbose = false;
@Option(name="-d", usage="Optional. Target DPI. Defaults to 300.",
required=false, multiValued=false)
private int targetDpi = 300;
@Argument
private List paths = new ArrayList();
private Image stampImage = null;
private static Image openImage(File f) throws BadElementException,
MalformedURLException, IOException {
return Image.getInstance(f.getAbsolutePath());
}
/**
* @return Answers a PdfReader for the File f.
*/
private static PdfReader openPdf(File f) throws IOException {
FileInputStream fIn = new FileInputStream(f);
PdfReader reader = null;
try {
PdfReader.unethicalreading = true;
reader = new PdfReader(fIn);
} finally {
fIn.close();
}
return reader;
}
/**
* @return Answers true if the first four bytes of File f match the
* PDF magic number - "%PDF".
*/
private static boolean isPdfFile(File f) throws IOException {
FileInputStream fIn = new FileInputStream(f);
byte[] magic = new byte[4];
boolean isPdf = false;
try {
fIn.read(magic);
isPdf = magic[0] == '%' && magic[1] == 'P'
&& magic[2] == 'D' && magic[3] == 'F';
} finally {
fIn.close();
}
return isPdf;
}
/**
* Close a PdfReader. Opposite of openPdf().
*/
private static void closePdf(PdfReader r) {
r.close();
}
/**
* @return Answers a PdfStamper for the PdfReader r, whose output will
* be placed in the File f.
*/
private static PdfStamper openStamper(File f, PdfReader r)
throws DocumentException, IOException {
FileOutputStream fOut = new FileOutputStream(f);
PdfStamper stamper = new PdfStamper(r, fOut);
return stamper;
}
/**
* Performs stamping of a PDF via a PdfStamper. An Image is inserted into
* the specified page number, 'page', along with a URL action for 'url',
* at the same location. The action area covers the the image.
* @throws IOException
*/
private void stampPdf(PdfStamper s, Image i, float x, float y, int page)
throws DocumentException, IOException {
/* Assume 72 DPI images if not specified. */
// final float scaleFactorX = (i.getDpiX() == 0 ? 72f : i.getDpiX()) / targetDpi;
// final float scaleFactorY = (i.getDpiY() == 0 ? 72f : i.getDpiY()) / targetDpi;
// final float scaledImgWidth = scaleFactorX * i.getWidth();
// final float scaledImgHeight = scaleFactorY * i.getHeight();
PdfContentByte content = s.getOverContent(page);
BaseFont font = BaseFont.createFont();
// BaseFont font = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
// String path = this.getClass().getResource("/").getPath();
// BaseFont font = BaseFont.createFont(path + "MSYH.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
ArrayList> waterMarkInfos = new ArrayList();
waterMarkInfos.add(new ArrayList(Arrays.asList(brand, url)));
waterMarkInfos.add(new ArrayList(Arrays.asList(" free download from ", "")));
waterMarkInfos.add(new ArrayList(Arrays.asList("text", "http://www.nicainicainizaicai.com")));
content.saveState();
for(ArrayList waterMarkInfo: waterMarkInfos){
String text = waterMarkInfo.get(0);
String brand_url = waterMarkInfo.get(1);
x = setTextToPdf(content, text, brand_url, font, page, x, y);
}
content.restoreState();
}
private static float setTextToPdf(PdfContentByte content, String text, String url, BaseFont font, int page, float x, float y) throws DocumentException{
if (content == null) {
throw new DocumentException("PDF does not have a page " + page + ".");
} else {
content.beginText();
float fontSize = 7;
// content.addImage(i, scaledImgWidth, 0.0f, 0.0f, scaledImgHeight, x, y);
float text_width = font.getWidthPoint(text, fontSize);
float text_height = font.getAscentPoint(text, fontSize) - font.getDescentPoint(text, fontSize);
if (!url.equals("")) {
content.setAction(new PdfAction(url),
x, y+text_height, x+text_width,
// y + scaledImgHeight,
// x + scaledImgWidth,
y);
content.setColorFill(BaseColor.BLUE);
}else{
content.setColorFill(BaseColor.GRAY);
}
//
content.setFontAndSize(font, fontSize);
//
// content.setTextMatrix(400, 880);
content.setTextMatrix(x, y);
content.showTextAligned(Element.ALIGN_LEFT, text, x, y, 0);
content.endText();
x = (float) (x + text_width);
return x;
}
}
/**
* Close a stamper. Opposite of openStamper().
*/
private static void closeStamper(PdfStamper s) throws DocumentException,
IOException {
s.close();
}
/**
* Add stamps to a PDF file. A stamped PDF is written to 'out'.
*/
private void addStampsToFile(File in, File out) {
try {
if (!isPdfFile(in)) {
if (verbose) {
System.err.println("Skipping " + in.getPath()
+ " because it doesn't look like a PDF file.");
}
return;
}
} catch (IOException e) {
System.err.println("Couldn't determine if " + in.getPath()
+ " is a PDF because of:");
System.err.println(e);
}
PdfReader r = null;
PdfStamper s = null;
try {
r = openPdf(in);
s = openStamper(out, r);
if (pages.contains(0)) {
pages.clear();
int i = 1;
for(; i < r.getNumberOfPages(); i++){
pages.add(i);
}
}
for (int page : pages) {
if (page < 0) {
page = r.getNumberOfPages() + 1 + page;
}
stampPdf(s, stampImage, stampLocation.x, stampLocation.y, page);
}
} catch (Exception e) {
System.err.println("Failed on " + in.getPath() + " because of:");
System.err.println(e);
} finally {
try {
if (s != null) {
closeStamper(s);
}
} catch (Exception e) {
}
try {
if (r != null) {
closePdf(r);
}
} catch (Exception e) {
}
}
}
/**
* @return Answers the output filename for file 'in'. This will change
* depending on command line argument values.
* rename
*/
private File getOutFileForInFile(File in) {
String[] parts = in.getName().split("\\.");
StringBuffer outName = new StringBuffer();
outName.append(parts[0]);
// outName.append('_');
outName.append(outputExtension);
for (int i=1; i'.');
outName.append(parts[i]);
}
File outParent = outputDirectory == null ? in.getAbsoluteFile()
.getParentFile()
: outputDirectory;
return new File(outParent.getPath() + File.separator + outName);
}
public static final void main(String... args) {
new Main().doMain(args);
}
private void doMain(String... args) {
CmdLineParser.registerHandler(StampTuple.class, StampTupleOptionHandler.class);
CmdLineParser parser = new CmdLineParser(this);
if (args.length == 0) {
System.err.println("Usage: pdfstamp [options] | " );
parser.printUsage(System.err);
System.exit(0);
}
try {
parser.parseArgument(args);
if (pages.size() == 0) {
/* Add a default page 1. */
pages.add(0);
}
// try {
// stampImage = openImage(imageFile);
// } catch (Exception e) {
// System.err.println("Couldn't open image file because of:");
// System.err.println(e);
// System.exit(0);
// }
for (String path : paths) {
File pathFile = new File(path);
if (pathFile.isDirectory()) {
iterateDirectory(pathFile);
} else {
addStampsToFile(pathFile,
getOutFileForInFile(pathFile));
}
}
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
}
}
private void iterateDirectory(File dir) {
for (String path : dir.list()) {
File pathFile = new File(dir.getPath() + File.separator + path);
if (pathFile.isDirectory() && recursive) {
iterateDirectory(pathFile);
} else {
addStampsToFile(pathFile,
getOutFileForInFile(pathFile));
}
}
}
}
코드 에는 jar 패키지 와 Image watermark 의 인터페이스 가 남아 있 습 니 다. stampPdf () 에 해당 하 는 설명 을 열 면 실행 할 수 있 습 니 다. 완벽 하 게 작업 을 마 칠 수 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.