繁体   English   中英

使用PDFBox将png图像转换为pdf时,PDF文档的宽度只有一半

[英]PDF Document is only half in width when converted a png image to pdf using PDFBox

我已经使用PDFBox将png图像转换为pdf文档,并且我能够成功做到这一点。

但是我遇到了一个问题,其中pdf文档仅显示图像宽度的50%(高度显示为完整)。请帮我解决这个问题。

我使用的代码如下:

public static void createPDFFromImage( String file, String image) throws IOException, COSVisitorException
    {
        PDDocument doc = null;
        try
        {
            doc = new PDDocument();
            PDPage page = new PDPage();
            doc.addPage( page );
            PDXObjectImage ximage = null;
            if( image.toLowerCase().endsWith( ".jpg" ) || image.toLowerCase().endsWith( ".jpeg" ))
            {        
                BufferedImage awtImage = ImageIO.read( new File( image ) );             
                ximage = new PDJpeg(doc, awtImage, 0 );
            }

            else
            {

                BufferedImage awtImage = new BufferedImage(250,250, BufferedImage.TYPE_INT_RGB);             
                awtImage = ImageIO.read(new FileImageInputStream(new File( image )));                              
                ximage = new PDPixelMap(doc, awtImage);
            }
            System.out.println(" Width of the image.... " + ximage.getWidth());
            PDPageContentStream contentStream = new PDPageContentStream(doc, page);   
            contentStream.drawImage( ximage, 20, 20);
            //contentStream.drawImage( ximage, 20, 20 );
            contentStream.close();
            doc.save( file );
       }
       finally
       {
            if( doc != null )
            {
                doc.close();
            }
       }
    } 

注意:每次保存时都会更改图像尺寸

请帮忙。 谢谢

这些代码可能对您有用。

    public void createPDFFromImage(String pdfFile, 
        List<String> imgList,int x, int y, float scale) throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();
        Iterator iter = imgList.iterator();
        int imgIndex=0;
        while(iter.hasNext()) {
            PDPage page = new PDPage();
            doc.addPage(page);

            BufferedImage tmp_image = ImageIO.read(new File(iter.next().toString()));
            BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);        
            image.createGraphics().drawRenderedImage(tmp_image, null);

            PDXObjectImage ximage = new PDPixelMap(doc, image);

            imgIndex++;


            PDPageContentStream contentStream = new PDPageContentStream(
                    doc, page,true,true);

            contentStream.drawXObject(ximage, x, y, ximage.getWidth()*scale, ximage.getHeight()*scale);

            contentStream.close();
        }
        doc.save(pdfFile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM