将图像添加到pdf从iText迁移到PDFBox

问题描述

在我们的项目中,我们使用iText 5.x版本来操纵PDF文件,并努力将其实现与PDFBox 2.x版本一起迁移。

在pdf页面方案中有一个添加图像,我已经尽我所能将代码转换为PDFBox。 :)在现有的实现(iText)中,他们使用PdfTemplate在模板中添加图像,并使用PdfAnnotation类在注释中添加模板。

我不知道如何使用PDFBox做到这一点。另外,请检查我是否正确迁移了现有的实现,因为我是使用Java在PDF库中的新手。

将图像添加到PDF(使用iText):

Document document = null;
        PdfReader pdfReader = null;
        
        pdfReader = new PdfReader(SourceFilePath());        
        
        //we retrieve the total number of pages and the page size
        int total = pdfReader.getNumberOfPages();
        Rectangle rectangle = pdfReader.getPageSizeWithRotation(1);
        
        document = new Document(rectangle);
        PdfImportedPage page;
        Pdfcopy.PageStamp stamp;
        
        // step 2: we create a Pdfcopy object that listens to the document.
        Pdfcopy copy = new Pdfcopy(document,new FileOutputStream(DestinationFilePath(false)); 
        
        document.open();
        
     // step 4: adding the content
        for (int i = 1; i <= total; i++) {
            page = copy.getImportedPage(pdfReader,i);
            if(i == 1 || aBarcodeVO.getdisplacementVO().isApplyForAllPages()){
                BufferedImage bufferedImage = getimage();
                
                Image img =  Image.getInstance(bufferedImage,null);
                img.scaletoFit(qrImageSize,qrImageSize);
    
                PdfName imgKey = new PdfName(aBarcodeVO.getImgUniqueId() + i);
                Rectangle rectPage = pdfReader.getPageSizeWithRotation(i);
                
                stamp = copy.createPageStamp(page);
    
                PdfImage stream = new PdfImage(img,"",null);
                stream.put(imgKey,imgKey);
                PdfIndirectObject ref = copy.addToBody(stream);
                
                int rotation = pdfReader.getPageRotation(i);
                Rectangle cropBoxRect = pdfReader.getCropBox(i);;
    
             
                
              //Explicitly Apply rotation to crop Box rectangle. 
                for (int j = 0; j < (rotation/90); j++) {
                    cropBoxRect = cropBoxRect.rotate();
                }
                
                
                
                //added Image in template and template in Annotation and finally annotation is added in PDF through Pdfcopy.PageStamp
                PdfTemplate template = PdfTemplate.createTemplate(copy,img.getPlainWidth(),img.getPlainHeight());
                img.setAbsolutePosition(0,0);
                img.setRotationdegrees(rotation);
                img.setDirectReference(ref.getIndirectReference());
                template.addImage(img);
    
                Rectangle rect = new Rectangle(rectLlx,rectLly,rectUrx,rectUry);
                rect.setBorderWidth(0.5f);
                rect.setBorderColor(new BaseColor(0xFF,0x00,0x00));
                
                PdfAnnotation annotation = PdfAnnotation.createStamp(copy,rect,null,"AnnotationOnly");
                annotation.setAppearance(PdfAnnotation.APPEaraNCE_norMAL,template);
                annotation.setFlags(PdfAnnotation.FLAGS_PRINT + PdfAnnotation.FLAGS_LOCKED);
                annotation.setRotate(rotation);
                PdfName annotKey = getAnnotKey(i);
                annotation.put(annotKey,annotKey);
                stamp.addAnnotation(annotation); 
                stamp.alterContents();
            }
            copy.addPage(page);
        }
        copy.freeReader(pdfReader);
        
        try {
            if (document != null) {
                document.close();
            }
        } catch (Exception e) {
            System.out.println("Exception in handleAddBarCode() while closing():document:" + e);
        }
        try {
            if (pdfReader != null) {
                pdfReader.close();
            }
        } catch (Exception e) {
            System.out.println("Exception in handleAddBarCode() while closing():pdfReader:" + e);
        }
    

将图像添加到PDF(使用PDFBox):

PDDocument pdDocument = PDDocument.load(new File(SourceFilePath()));
int total = pdDocument.getNumberOfPages();

PDPage page = pdDocument.getDocumentCatalog().getPages().get(0);
PDRectangle rectangle = getRotatedMediaBox(page);

PDPage pdPage = new PDPage(rectangle);
PDDocument newDocument = new PDDocument();
for (int i = 0; i < total; i++) {
    pdPage = newDocument.importPage(pdDocument.getPage(i));
    PDRectangle pageRect = getRotatedMediaBox(pdPage);
    
    int rotation = pdPage.getRotation();
    
    PDRectangle cropBoxRect =  page.getCropBox();
    
    //Calculate margin between crop Box rectangle and page rectangle.
    float[] margins = getCropBoxMargin(pageRect,cropBoxRect,rotation);
    
    if (rotation == 90 || rotation == 270) {
        cropBoxRect = new PDRectangle(cropBoxRect.getLowerLeftY(),cropBoxRect.getLowerLeftX(),cropBoxRect.getHeight(),cropBoxRect.getWidth());
    }
    
    
    BufferedImage bufferedImage = getimage();
    PDPageContentStream pageContentStream = new PDPageContentStream(newDocument,pdPage,PDPageContentStream.AppendMode.APPEND,true);
    PDImageXObject image = JPEGFactory.createFromImage(newDocument,bufferedImage);
    
    if (rotation == 90 || rotation == 270) {
        Matrix matrix = Matrix.getRotateInstance(Math.toradians(rotation),0);
        PDRectangle cropBox = pdPage.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;

        Rectangle rectang = cropBox.transform(matrix).getBounds();
        float scale = Math.min(cropBox.getWidth() / (float)rectang.getWidth(),cropBox.getHeight() / (float)rectang.getHeight());

        pageContentStream.transform(Matrix.getTranslateInstance(tx,ty));
        pageContentStream.transform(matrix);
        pageContentStream.transform(Matrix.getScaleInstance(scale,scale));
        pageContentStream.transform(Matrix.getTranslateInstance(-tx,-ty));
    }
    
    pageContentStream.drawImage(image,rectLlx,qrImageSize,qrImageSize);
    pageContentStream.close();
}
newDocument.save(new File(DestinationFilePath(false)));

newDocument.close();
pdDocument.close();

请为此提供帮助,或者至少期待您对纠正PDFBox实现的代码提出建议。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)