LoginSignup
1
10

More than 5 years have passed since last update.

PDFファイルの結合や画像埋め込み

Posted at

殆ど覚書なので中途半端ですが。

pom.xml
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.4</version>
</dependency>
PDFCtrlSample.java
/**
 * PDF操作のサンプル
 * @author ryutaro_hakozaki
 */
public class PDFCtrlSample {

    public static void main(String argv[]){

        PDFCtrlSample controller = new PDFCtrlSample();

        /**
         * PDFファイルを結合する
         */
        try {
            File f1 = new File("D:\\ファイル其の一.pdf");
            File f2 = new File("D:\\ファイル其の二.pdf");
            ByteArrayOutputStream out = controller.PDFCombine(f1,f2);
            FileOutputStream fos = new FileOutputStream("D:\\結合後.pdf");
            out.writeTo(fos);
            fos.close();
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(PDFCtrlSample.class.getName()).log(Level.SEVERE, null, ex);
        }

        /**
         * PDFファイルにスタンプを貼る
         */
        try {
            File f1 = new File("D:\\貼付対象PDF.pdf");
            File f2 = new File("D:\\ロゴ.png");
            controller.addStamp(f1, f2, 300, 300);
        } finally {
            //
        }        

    }

    /**
     * 複数のPDFを1つに結合する
     * @param inputFiles
     * @return 結合結果をバイナリで返す
     */
    public ByteArrayOutputStream PDFCombine(File... inputFiles){
        ByteArrayOutputStream o = new ByteArrayOutputStream();
        List<PDDocument> pddHolder = new ArrayList<>();

        try(PDDocument combiledPDFdoc= new PDDocument()){
            for(File f : inputFiles){
                try{
                    PDDocument pf = PDDocument.load(f);
                    for(PDPage p : pf.getPages()) combiledPDFdoc.addPage(p);
                    pddHolder.add(pf);
                } catch (IOException ex) {
                    Logger.getLogger(PDFCtrlSample.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            combiledPDFdoc.save(o);
            // Save後に開放可能、Save前に開放すると上手く動かない
            pddHolder.stream().sequential().forEach(item -> {
                try {item.close();} catch (IOException ex) {}
            });
        } catch (IOException ex) {
            Logger.getLogger(PDFCtrlSample.class.getName()).log(Level.SEVERE, null, ex);
        } 
        return o;
    }

    /**
     * 画像イメージをPDFに貼付する
     * 1ページ目限定
     * @param pdf 対象のPDFファイル
     * @param image 貼付したいイメージファイル
     * @param xPosition 貼付位置(X)
     * @param yPosition 貼付位置(Y)
     */
    public void addStamp(File pdf, File image, float xPosition, float yPosition){
        this.addStamp(pdf, image, xPosition, yPosition, 0, 0);
    }

    /**
     * 画像イメージをPDFに貼付する
     * 1ページ目限定
     * @param pdf 対象のPDFファイル
     * @param image 貼付したいイメージファイル
     * @param xPosition 貼付位置(X)
     * @param yPosition 貼付位置(Y)
     * @param width イメージの幅
     * @param height イメージの高さ
     */
    public void addStamp(File pdf, File image, float xPosition, float yPosition, float width, float height){
        float stampWidth = 0;
        float stampHeight = 0;
        try(PDDocument pf = PDDocument.load(pdf)){
            PDImageXObject stamp = PDImageXObject.createFromFileByContent(image, pf);
            stampWidth = width == 0 ? stamp.getWidth() : width;
            stampHeight = height == 0 ? stamp.getHeight() : height;
            try(PDPageContentStream contentStream = new PDPageContentStream(pf, pf.getPage(0), PDPageContentStream.AppendMode.APPEND, true, true)){
                contentStream.drawImage(stamp, xPosition, yPosition, stampWidth, stampHeight);
            } finally {
                pf.save(pdf);
                pf.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(PDFCtrlSample.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

1
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
10