PDFBox图像大小问题
问题描述:
我新来使用PdfBox,并且在显示图像时遇到小问题。我能够导入大小为800 * 900像素的图像,并且在以100%的现有PDF查看时看起来很好。但是,当使用下面的代码生成生成的PDF时,图像变得模糊,并且图像超出了A4页面的边界。PDFBox图像大小问题
是否有不同的尺寸/保存图像的方式,以便它们在pdfbox中正确显示?
public class PDFtest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, COSVisitorException {
// TODO code application logic here
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
InputStream in = new FileInputStream(new File("img.jpg"));
PDJpeg img = new PDJpeg(document, in);
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.drawImage(img, 10, 700);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(10, 650);
contentStream.drawString("Hello World");
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
document.close();
}
答
如果你的目的是在一个PDF的A4大小的PIC,然后我想你已经发现典型A4的实际像素尺寸。
你也应该知道,要查看像JPG,GIF,BMP或图片的延伸......
从我在你的代码看到,画面的尺寸为10 X 700我相信这是相当小的尺寸。
contentStream.drawImage(img, 10, 700);
而且图片的扩展名是:JPG
InputStream in = new FileInputStream(new File("img.jpg"));
检查这些并返回更多信息。
就是这样。 祝你好运'''
答
我在这个问题中提出了同样的问题,但给出的答案是不正确的。
经过一番研究,我找到了一个解决方案。
除了使用功能的drawImage使用该功能的drawXObject
contentStream.drawXObject(img, 10, 700, 100, 100);
其中最后两个数字指定要绘制的图像的大小。
答
我想指出,从2.0开始,在Victor的答案中的contentStream.drawXObject
函数调用已被弃用。如果你想指定一个宽度和高度,你应该应该使用contentStream.drawImage(image, x, y, width, height)
你现在的第一部分,我认为这将是如此简单。在发布之前2秒,我意识到最大宽度为595像素,像素密度较低。 关于(img,10,700)图像尺寸取自实际的jpeg,然后这两个数字代表和x,y坐标到图像的绘制位置而不是图像尺寸。 –
阿哈我看到了,无论如何,你已经发现你的错误,只要记住你从这个错误中学习。 – user2624929
@ user2624929 here contentStream.drawImage(img,10,700); 10X700不是图像大小,它是图像应该出现的位置,意味着X,Y坐标。你能告诉我怎样才能使我的图像尺寸100X100,适合在那个位置? – androidGenX