PDFBoxでPDFに画像を差し込む

PDFBoxを使うと、既存のPDFにjpg画像を差し込むことができる。実装例としてはここにあるけど、以下のような感じ。

PDDocument doc = null;
try
{
    doc = PDDocument.load( inputFile );
    //we will add the image to the first page.
    PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
    PDXObjectImage ximage = null;
    if( image.toLowerCase().endsWith( ".jpg" ) )
    {
        ximage = new PDJpeg(doc, new FileInputStream( image ) );
    }
    else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
    {
        ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
    }
    else
    {
        //BufferedImage awtImage = ImageIO.read( new File( image ) );
        //ximage = new PDPixelMap(doc, awtImage);
        throw new IOException( "Image type not supported:" + image );
    }
    PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
    contentStream.drawImage( ximage, 20, 20 );
    contentStream.close();
    doc.save( outputFile );
}
finally
{
    if( doc != null )
    {
        doc.close();
    }
}

ポイントは

  • contentStreamの前にximageを取得しておくこと
  • drawImageが左下から始まっていること

かな。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です