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

时间:2013-10-09 11:12:02

标签: java pdf-generation document 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();
            }
       }
    } 

注意:每次保存时图像的尺寸都会发生变化

请帮忙。 感谢

1 个答案:

答案 0 :(得分:0)

这些代码可能对您有所帮助。

    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();
        }
    }
}