Hello friends,
I am facing some problem while printing the page from my swings application.Below is my
java code which i am using for printing the pdf file. The print dilog box appears but if i change the attributes or margins it is not reflecting in my print.
Please help me in finding the problem with my code.
File file = new File(sFilePath);
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
PDFFile pdfFile = new PDFFile(bb);
PrintUtility pages = new PrintUtility(pdfFile);
// Create Print Job
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
pjob.setJobName(file.getName());
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
boolean blPrintJob = pjob.printDialog(aset);
if (blPrintJob) {
pjob.print(aset);
}
class PrintUtility extends PDFPrintPage {
private PDFFile file;
PrintUtility(PDFFile file) {
super(file);
this.file = file;
}
public int print(Graphics g, PageFormat format, int index)
throws PrinterException {
int pagenum = index + 1;
// don't bother if the page number is out of range.
if ((pagenum >= 1) && (pagenum <= file.getNumPages())) {
// fit the PDFPage into the printing area
Graphics2D g2 = (Graphics2D) g;
PDFPage page = file.getPage(pagenum);
double pwidth = format.getImageableWidth();
double pheight = format.getImageableHeight();
double aspect = page.getAspectRatio();
double paperaspect = pwidth / pheight;
Rectangle imgbounds;
if (aspect > paperaspect) {
// paper is too tall / pdfpage is too wide
int height = (int) (pwidth / aspect);
imgbounds = new Rectangle(
(int) format.getImageableX(),
(int) (format.getImageableY()), //+ ((pheight - height) / 2)),
(int) pwidth,
height);
} else {
// paper is too wide / pdfpage is too tall
int width = (int) (pheight * aspect);
imgbounds = new Rectangle(
(int) (format.getImageableX()),// + ((pwidth - width) / 2)),
(int) format.getImageableY(),
width,
(int) pheight);
}
// render the page
PDFRenderer pgs = new PDFRenderer(page, g2, imgbounds, null, null);
try {
page.waitForFinish();
pgs.run();
} catch (InterruptedException ie) {
}
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
}
Thanks,
Sanjay