我使用pdfbox库2.0.16编写了一些Java代码,以精确的坐标(x,y)打印rect。
我想用毫米表示坐标。
我使用以下方法以pdfbox单位转换mm:
public static float getInc(float mm)
{
return mm / (25.4f / 72f);
}
所以我制作了文档和页面
float page_w_mm = 210f;
float page_h_mm = 297f;
PDDocument doc = new PDDocument();
PDRectangle pageSize = new PDRectangle(PDFUtils.getInc(page_w_mm), PDFUtils.getInc(page_h_mm));
PDPage page1 = new PDPage(pageSize);
page1.setMediaBox(pageSize);
page1.setCropBox(pageSize);
并使用此方法打印矩形
public static void drawRect(PDPageContentStream content, float x_mm, float y_mm) {
..
float w = 3;
float h = 3;
content.addRect(getInc(x_mm), getInc(y_mm), getInc(w), getInc(h));
PDColor black = new PDColor(new float[]
{
0, 0, 0
}, PDDeviceRGB.INSTANCE);
content.setNonStrokingColor(black);
content.fill();
..}
然后关闭页面,文档等。我尝试使用此代码进行打印
String printerNameDesired = "MYPrinter";
PrintService[] service = PrinterJob.lookupPrintServices();
DocPrintJob docPrintJob = null;
for (int i = 0; i < service.length; i++) {
System.out.println(service[i].getName());
if (service[i].getName().equalsIgnoreCase(printerNameDesired ))
{
docPrintJob = service[i].createPrintJob();
break;
}
}
try {
final HashPrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
attrs.add( new MediaPrintableArea(0, 0, page_w_mm, page_h_mm,
MediaPrintableArea.MM));
PrinterJob pjob = PrinterJob.getPrinterJob();
Paper paper = pjob.defaultPage().getPaper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pjob.setPrintService(docPrintJob.getPrintService());
pjob.setJobName("job");
pjob.setPageable(new PDFPageable(doc));
pjob.print(attrs);
问题在于,在打印文档时,x rect坐标总是正确的,但是y rect坐标是错误的(总是比指示的大约多4mm)
为什么?