我是新手使用PdfBox,我在显示图像时遇到一个小问题.我能够导入大小为800*900像素的图像,并且在现有pdf中以100%查看时看起来很好.但是,使用以下代码生成生成的PDF时,图像会变得模糊,图像会超出A4页面的边界.
是否有不同的方法来调整/保存图像,以便它们在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();
}
Run Code Online (Sandbox Code Playgroud)
我想指出,从 2.0 开始,contentStream.drawXObject不推荐使用 Victor 的答案中的函数调用。如果要指定宽度和高度,则应使用contentStream.drawImage(image, x, y, width, height)
我在这个问题上遇到了同样的问题,但给出的答案是不正确的.
经过一番研究,我找到了解决方案.
而不是使用函数drawImage使用函数drawXObject
contentStream.drawXObject( img, 10, 700, 100, 100 );
Run Code Online (Sandbox Code Playgroud)
最后两个数字指定要绘制的图像的大小.
小智 0
如果您的目的是在 PDF 上添加 A4 尺寸的图片,那么我猜您会找到典型 A4 的实际尺寸(以像素为单位)。
此外,您还应该注意要查看的图片的扩展名,例如 jpg、gif 或 bmp ...
从我在你的代码中看到的,图片的尺寸是 10 X 700,我认为这是相当小的尺寸。
contentStream.drawImage(img, 10, 700);
Run Code Online (Sandbox Code Playgroud)
图片的扩展名是:jpg
InputStream in = new FileInputStream(new File("img.jpg"));
Run Code Online (Sandbox Code Playgroud)
检查这些并返回以获取更多信息。
就这样。祝你好运'''