Itext rectangle from milimeters

2.9k views Asked by At

I try draw a A5 rentangle in a PDF with Itext using Rectangle class and Utilities.milimetersToPoints method but when i print the PDF and measure the rectangle the measurments is not the A5 dimensions.

public static boolean createPDF(String pathPDF) {

    Document document = new Document(PageSize.A4);

    try {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pathPDF));
        writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
        document.open();

        createRectangle(writer, 30.75f, 11, 148.5f, 210, Color.RED);
        document.close();

    } catch (Exception e) {
        logger.error("Error , e);
        return false;
    } 

    return true;

}

private static void createRectangle(PdfWriter writer, float x, float y, float width, float height, Color color) {
    float posX = Utilities.millimetersToPoints(x);
    float posY = Utilities.millimetersToPoints(y);

    float widthX = Utilities.millimetersToPoints(width+x);
    float heightY = Utilities.millimetersToPoints(height+y);

    Rectangle rect = new Rectangle(posX, posY, widthX, heightY);

    PdfContentByte canvas = writer.getDirectContent();
    rectangle.setBorder(Rectangle.BOX);
    rectangle.setBorderWidth(1);
    rectangle.setBorderColor(color);
    canvas.rectangle(rectangle);

}

what i'm doing wrong?

I use Itext 2.1.7 Many Thanks

1

There are 1 answers

4
mkl On BEST ANSWER

I just ran your SSCCE (Short, Self Contained, Correct (Compilable), Example), and printed the resulting PDF from Adobe Reader. I measured the red rectangle both on-screen using the Adobe Reader measuring tool and on-paper.

Screenshot of measurement on-screen

The result on screen:

Excerpt of screenshot of measurement on-screen

matches your parameters

createRectangle(writer, 30.75f, 11, 148.5f, 210, Color.RED);
------------------------------------^^^^^^--^^^

exactly, and the measurement on-paper matches as exactly as measurement with rulers can be.


Possible causes of the problem on your side:

  1. I use a current iText version. But while there have been quite a lot of improvements and fixes since 2.1.7, I doubt any fixes had been applied here.

  2. Different printers; some printers are known to scale while printing.

  3. Different viewer from which you print; some viewers may always scale.

  4. Different scaling settings in printer dialog.