此类创建PDF并将其转换为PNG文件。 print()函数应在系统默认打印机(Canon Shelby CP1300)上打印PNG。不幸的是,图像打印得很小(0.5x1cm)。 如果我在Windows资源管理器中打印PNG文件,则一切正常。 实际上,我创建的PNG文件的DPI为300,但最后只有92dpi。 我是否需要其他“ PrintRequestAttributes”来解决此问题?还是可以让png文件适合所需的页面大小?
public PrintableImage(Photos photos) {
this.setPageSize(PageSize.ID_1.rotate());
createPdfWith(photos);
convertToPNG();
}
private void createPdfWith(Photos photos) {
try {
Image img;
PdfWriter.getInstance(this, new FileOutputStream(Constants.TEMP_PRINTFOLDER + Constants.TMP_PRINT_PDF));
this.open();
int offsetPhotos = 0;
for (int i = photos.size() - 1; i >= 0; i--) {
String image = photos.get(i).getPath();
img = Image.getInstance(image);
img.scaleToFit(Constants.SIZE_IMAGE);
img.setAbsolutePosition(getPositionForCentering(img), offsetPhotos + 40);
this.add(img);
offsetPhotos = 95;
}
img = Image.getInstance(Constants.PATH_LOGO);
img.scaleToFit(Constants.SIZE_LOGO);
img.setAbsolutePosition(getPositionForCentering(img) + 4, 14);
this.add(img);
this.close();
} catch (Exception e) {
}
}
private float getPositionForCentering(Image image) {
return (getPageSize().getWidth() - image.getScaledWidth()) / 2;
}
private void convertToPNG() {
try {
PDDocument doc = PDDocument.load(new File(Constants.TEMP_PRINTFOLDER + Constants.TMP_PRINT_PDF), "");
PDFRenderer pdfRenderer = new PDFRenderer(doc);
BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
File pngFile = new File(Constants.TEMP_PRINTFOLDER + Constants.TMP_PRINT_PNG);
ImageIO.write(image, "png",pngFile);
} catch (IOException e) {
}
}
/**
* Prints the last created PNG-Image
*/
public static void print() {
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(OrientationRequested.PORTRAIT);
try {
FileInputStream pngFile = new FileInputStream(Constants.TEMP_PRINTFOLDER + Constants.TMP_PRINT_PNG);
Doc pngDoc = new SimpleDoc(pngFile, DocFlavor.INPUT_STREAM.PNG, null);
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = printService.createPrintJob();
printJob.print(pngDoc, attributes);
pngFile.close();
} catch (Exception e) {
}
}
}
非常感谢!