我正在尝试从 JPEG、BMP 类型的图像生成 PDF,但我得到右侧图像的一部分总是被截断。我正在使用默认的 Windows 图片 Sunset.jpg 之一。
下面是代码:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDCcitt;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;
public class ImageToPDF
{
public 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 if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
}
else
{
BufferedImage awtImage = new BufferedImage(1000, 800, 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.close();
doc.save( file );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}
public static void main(String[] args)
{
ImageToPDF app = new ImageToPDF();
try
{
app.createPDFFromImage( "C:\\test1.pdf", "C:\\Sunset.jpg");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
请帮助我纠正我做错的事情。