pdf 워 터 마크, 텍스트, 그림, 하이퍼링크, 자바 itext, 여기 원 하 는 모든 것 이 있 습 니 다.

25005 단어 python자바
최근 회사 사이트 의 pdf 는 우리 자신의 워 터 마크 를 추가 하고 여러 번 review 로 워 터 마크 를 하고 링크 를 하 는 방법 이 필요 합 니 다. windows 의 A - PDF 는 수 요 를 만족 시 킬 수 있 습 니 다. 예전 에 사이트 팀 도 이런 방법 으로 만 들 었 지만 효율 이 비교적 낮 습 니 다. 회사 의 pdf 의 다른 처리 논 리 는 분포 식 Liux 시스템 에 배치 되 었 기 때문에 일치 성과 효율 을 높이 기 위해 여러 번 구 글 과 도 모 –(대부분의 블 로 그 는 pdf 에 문자 워 터 마크 를 찍 는 기능 만 실 현 했 을 뿐 대동소이 하 다. 딱 봐 도 서로 베 끼 는 것) 우연히 자바 의 itext 가방 을 발견 하고 github 에서 오픈 소스 가 실행 가능 한 jar 가방 을 다운로드 하여 기 똥 차!! 그의 일부 코드 를 수정 하여 수 요 를 실현 했다.
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 () 에 해당 하 는 설명 을 열 면 실행 할 수 있 습 니 다. 완벽 하 게 작업 을 마 칠 수 있 습 니 다.

좋은 웹페이지 즐겨찾기