Hot questions for Using PDFBox in swing

Question:

I'm new in Apache PDFBox, I used org.apache.pdfbox.PDFReader to open PDF and etc, but now I need to show in JFrame PDF documents all pages in one JPanel, is it possible?


Answer:

As described before I needed to show all pages of PDF document in a jframe, for it I have used org.apache.pdfbox.PDFReader as follow:

import java.awt.*;
import java.lang.reflect.*;
import java.util.List;

import javax.swing.*;

import org.apache.pdfbox.PDFReader;
import org.apache.pdfbox.pdfviewer.PageWrapper;
import org.apache.pdfbox.pdmodel.PDPage;

public class CustomPDFReader extends PDFReader {
/**
 * 
 */
private static final long serialVersionUID = 678451510308887925L;

public CustomPDFReader() {
    super();
}

public void setCurrentFile(String file) {
    try {
        Method m = getClass().getSuperclass().getDeclaredMethod("openPDFFile", 
                new Class<?>[]{String.class, String.class});
        m.setAccessible(true);
        m.invoke(this, file, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String []args) {
    CustomPDFReader reader = new CustomPDFReader();
    // remove menubar
    JMenuBar menu = reader.getJMenuBar();
    menu.setVisible(false);

    JPanel header = new JPanel(new BorderLayout());

    JPanel firstLine = new JPanel();

    JLabel label = new JLabel("Label");
    firstLine.add(label);

    JPanel secondLine = new JPanel();

    JTextField text = new JTextField();
    text.setPreferredSize(new Dimension(100, 30));
    secondLine.add(text);

    JButton button = new JButton("Button");
    button.setPreferredSize(new Dimension(100, 30));
    secondLine.add(button);

    header.add(firstLine, java.awt.BorderLayout.NORTH);
    header.add(secondLine, java.awt.BorderLayout.SOUTH);

    reader.getContentPane().add(header, java.awt.BorderLayout.NORTH);

    // set default opened file
    reader.setCurrentFile("test.pdf");
    reader.showAllPages();
    reader.setVisible(true);
}

private void showAllPages() {
    try {
        Field pages = getClass().getSuperclass().getDeclaredField("pages");
        pages.setAccessible(true);
        List<PDPage> pagesList = (List<PDPage>) pages.get(this);

        Field documentPanel = getClass().getSuperclass().getDeclaredField("documentPanel");
        documentPanel.setAccessible(true);
        JPanel panel = (JPanel) documentPanel.get(this);
        panel.remove(0);
        GridLayout layout = new GridLayout(0, 1);
        panel.setLayout(layout);
        for(PDPage page : pagesList) {
            PageWrapper wrapper = new PageWrapper(this);
            wrapper.displayPage(page);
            panel.add(wrapper.getPanel());
        }
        pack();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

}

PDFBox version is 1.8.10. Sample project you can find there

Question:

I am trying to get the current page no using PDF box reader.

Hear is what i have written the code.

public class PDFTextExtractor{

ArrayList extractText(String fileName) throws Exception {

PDDocument document = null;
try {
    document = PDDocument.load( new File(fileName) );
    PDFTextAnalyzer stripper = new PDFTextAnalyzer();
    stripper.setSortByPosition( true );
    stripper.setStartPage( 0 );
    stripper.setEndPage( document.getNumberOfPages() );
    Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
    stripper.writeText(document, dummy);
    return stripper.getCharactersList();
}
finally {
    if( document != null ) {
        document.close();
    }
}

}

And when i am trying to get the details i am writing the following code.

public class PDFTextAnalyzer extends PDFTextStripper {

    public PDFTextAnalyzer() throws IOException {
        super();
        // TODO Auto-generated constructor stub
    }

    private ArrayList<CharInfo> charactersList = new ArrayList<CharInfo>();

    public ArrayList<CharInfo> getCharactersList() {
        return charactersList;
    }

    public void setCharactersList(ArrayList<CharInfo> charactersList) {
        this.charactersList = charactersList;
    }

    @Override
    protected void writeString(String string, List<TextPosition> textPositions)
            throws IOException {

        System.out.println("----->"+document.getPages().getCount());

/*      for(int i = 0 ; i < document.getPages().getCount();i++)
        {
        */
        float docHeight = +document.getPage(1).getMediaBox().getHeight();
        for (TextPosition text : textPositions) {
            /*
             * System.out.println((int)text.getUnicode().charAt(0)+" "+text.
             * getUnicode()+ " [(X=" + text.getXDirAdj()+" "+text.getX() + ",Y="
             * + text.getYDirAdj() + ") height=" + text.getHeightDir() +
             * " width=" + text.getWidthDirAdj() + "]");
             */

            System.out.println("<-->"+text.toString());
            charactersList.add(new CharInfo(
                    text.getUnicode(), 
                    text.getXDirAdj(),
                    docHeight - text.getYDirAdj(),
                    text.getWidthDirAdj(),
                    text.getHeightDir(),
                    text.getFontSizeInPt(),
                    1,     // Page number of current text
                    text.getFont().getFontDescriptor().getFontName(), 
                    text.getFont().getFontDescriptor().getFontFamily()
                )
            );

        }

But i am unable to fetch the page number. See the line comment "Page number of current text".Is there any way to fetch the page number.


Answer:

How about this.getCurrentPageNo()?

Question:

I have a PDF file that I converted into an image. Was able to write on top of the image but when I tried to save the shapes/lines into the pdf, the point are not their place and the shapes are inverted.

This is what I draw.

This is the saved PDF File.

I'm really sorry but that is the shortest code I can make in order replicate the problem.

I know this question is not good but I hope someone can help.

Thank you Tilman Hausherr for your patience..

   package pdfwriter;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

public class Example {

    private static class MyImagePanel extends JPanel {

        final BufferedImage image;
        final float scale = .38f;
        AffineTransform atg;
        Point start = new Point();
        Point end = new Point();
        boolean isNewLine = true;
        static ArrayList<Line2D> lines = new ArrayList<>();
        static PDDocument document;

        public MyImagePanel() throws IOException {

            document = PDDocument.load(new File("path"));
            PDFRenderer renderer = new PDFRenderer(document);
            image = renderer.renderImageWithDPI(0, 200, ImageType.RGB);

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    if (end != start) {
                        Line2D line = new Line2D.Float(start.x, start.y, end.x, end.y);
                        lines.add(line);
                        Point2D p = calcCoordinates(e);
                        start = new Point();
                        start.x = (int) p.getX();
                        start.y = (int) p.getY();
                        repaint();
                    }

                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    Point2D p = calcCoordinates(e);
                    end = new Point();

                    end.x = (int) p.getX();
                    end.y = (int) p.getY();
                    repaint();
                }
            });
        }

        private Point2D calcCoordinates(MouseEvent e) {
            Point p = new Point(e.getX(), e.getY());
            try {
                return atg.inverseTransform(p, null);
            } catch (NoninvertibleTransformException ex) {
                return p;
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2D = (Graphics2D) g.create();

            double affineX = (getWidth() - scale * image.getWidth()) / 2;
            double affineY = (getHeight() - scale * image.getHeight()) / 2;

            AffineTransform at = new AffineTransform();
            at.translate(affineX, affineY);
            at.scale(scale, scale);

            AffineTransform atf = g2D.getTransform();
            atf.concatenate(at);

            atg = (AffineTransform) atf.clone();

            g2D.setTransform(atf);

            g2D.drawImage(image, 0, 0, this);
            try {
                g2D.drawLine(start.x, start.y, end.x, end.y);
            } catch (NullPointerException e) {

            }

            for (Line2D l : lines) {
                g2D.draw(l);
            }

            g2D.dispose();
        }

        public static void save() {

            try {
                PDPage page = document.getPage(0);

                PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);

                for (Line2D l : lines) {
                    contentStream.moveTo((float) l.getX1(), (float) l.getY1());
                    contentStream.lineTo((float) l.getX2(), (float) l.getY2());
                    contentStream.stroke();
                }

                contentStream.close();

                document.save(
                        new File("path"));
                document.close();
            } catch (IOException ex) {
                Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        @Override
        public Dimension getPreferredSize() {
            int width = (int) (scale * image.getWidth());
            int height = (int) (scale * image.getHeight());
            return new Dimension(width, height);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("PDF");
        frame.setSize(1500, 1200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        MyImagePanel imagePanel = null;
        try {
            imagePanel = new MyImagePanel();
        } catch (IOException ex) {
            Logger.getLogger(Example.class
                    .getName()).log(Level.SEVERE, null, ex);
        }

        JButton btn = new JButton("Save");

        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MyImagePanel.save();
            }
        });

        btn.setBounds(10, 0, 70, 30);

        frame.add(btn);
        JPanel pnl = new JPanel();
        pnl.add(imagePanel);
        pnl.setBounds(0, 100, 1500, 1200);
        frame.add(pnl);
        frame.revalidate();
        frame.repaint();
        frame.setVisible(true);
    }

}

Answer:

PDF coordinates start at the bottom. So you have to deduct it from the page height. (And if there is a cropbox, then it's a bit more complex, you'd have to add the origins to the calculated coordinates, because the cropbox is what you see). And you need to reverse the inverse-transform from calcCoordinates => transform.

So the code should look like this:

for (Line2D l : lines)
{
    Point2D p1 = new Point2D.Double(l.getX1(), l.getY1());
    Point2D p2 = new Point2D.Double(l.getX2(), l.getY2());
    p1 = atg.transform(p1, null);
    p2 = atg.transform(p2, null);
    contentStream.moveTo((float) p1.getX(), page.getMediaBox().getHeight() - (float) p1.getY());
    contentStream.lineTo((float) p2.getX(), page.getMediaBox().getHeight() - (float) p2.getY());
    contentStream.stroke();
}

To make that work, atg must be accessible, for that I removed "static" from "save", and added a "return" in the exception handler, and changed MyImagePanel.save() to imagePanel.save();.

But wait, there's more... somehow the lines don't fit fully. There is a slight difference... the reason: scale is not .38, it is about .36 (72 / 200), 200 being your dpi. Your mistake was to have two fixed values that depend on each other, but this dependence wasn't in the code. Your code should have something like this:

final int DPI = 200;
final float scale = 72f / DPI;

Full code:

public class SO57387803DrawShapesInPDF
{

    private static class MyImagePanel extends JPanel
    {

        final BufferedImage image;
        //final float scale = .38f;
        final int DPI = 200;
        final float scale = 72f / DPI;

        AffineTransform atg;
        Point start = new Point();
        Point end = new Point();
        boolean isNewLine = true;
        static ArrayList<Line2D> lines = new ArrayList<>();
        static PDDocument document;

        public MyImagePanel() throws IOException
        {
            document = PDDocument.load(new File("XXXX.pdf"));
            PDFRenderer renderer = new PDFRenderer(document);
            image = renderer.renderImageWithDPI(0, DPI, ImageType.RGB);

            addMouseListener(new MouseAdapter()
            {
                @Override
                public void mouseReleased(MouseEvent e)
                {
                    if (end != start)
                    {
                        Line2D line = new Line2D.Float(start.x, start.y, end.x, end.y);
                        lines.add(line);
                        Point2D p = calcCoordinates(e);
                        start = new Point();
                        start.x = (int) p.getX();
                        start.y = (int) p.getY();

                        repaint();
                    }

                }
            });
            addMouseMotionListener(new MouseMotionAdapter()
            {
                @Override
                public void mouseMoved(MouseEvent e)
                {
                    Point2D p = calcCoordinates(e);
                    end = new Point();

                    end.x = (int) p.getX();
                    end.y = (int) p.getY();
                    repaint();
                }
            });
        }

        private Point2D calcCoordinates(MouseEvent e)
        {
            Point p = new Point(e.getX(), e.getY());
            try
            {
                return atg.inverseTransform(p, null);
            }
            catch (NoninvertibleTransformException ex)
            {
                return p;
            }
        }

        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);

            Graphics2D g2D = (Graphics2D) g.create();

            double affineX = (getWidth() - scale * image.getWidth()) / 2;
            double affineY = (getHeight() - scale * image.getHeight()) / 2;

            AffineTransform at = new AffineTransform();
            at.translate(affineX, affineY);
            at.scale(scale, scale);

            AffineTransform atf = g2D.getTransform();
            atf.concatenate(at);
            atg = (AffineTransform) at.clone();

            g2D.setTransform(atf);

            g2D.drawImage(image, 0, 0, this);
            try
            {
                g2D.drawLine(start.x, start.y, end.x, end.y);
            }
            catch (NullPointerException e)
            {

            }

            for (Line2D l : lines)
            {
                g2D.draw(l);
            }

            g2D.dispose();
        }

        public void save()
        {

            try
            {
                PDPage page = document.getPage(0);

                PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);

                for (Line2D l : lines)
                {
                    Point2D p1 = new Point2D.Double(l.getX1(), l.getY1());
                    Point2D p2 = new Point2D.Double(l.getX2(), l.getY2());
                    p1 = atg.transform(p1, null);
                    p2 = atg.transform(p2, null);
                    //contentStream.moveTo((float) l.getX1(), (float) l.getY1());
                    //contentStream.lineTo((float) l.getX2(), (float) l.getY2());
                    contentStream.moveTo((float) p1.getX(), page.getMediaBox().getHeight() - (float) p1.getY());
                    contentStream.lineTo((float) p2.getX(), page.getMediaBox().getHeight() - (float) p2.getY());
                    contentStream.stroke();
                }

                contentStream.close();

                document.save(new File("saved.pdf"));
                document.close();
            }
            catch (IOException ex)
            {
                Logger.getLogger(SO57387803DrawShapesInPDF.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        @Override
        public Dimension getPreferredSize()
        {
            int width = (int) (scale * image.getWidth());
            int height = (int) (scale * image.getHeight());
            return new Dimension(width, height);
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new JFrame("PDF");
        frame.setSize(1500, 1200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        // MyImagePanel imagePanel = null;
        MyImagePanel imagePanel;
        try
        {
            imagePanel = new MyImagePanel();
        }
        catch (IOException ex)
        {
            Logger.getLogger(SO57387803DrawShapesInPDF.class
                    .getName()).log(Level.SEVERE, null, ex);
            return; // or there would be an uninitialized variable
        }

        JButton btn = new JButton("Save");

        btn.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                imagePanel.save();
                //MyImagePanel.save();
            }
        });

        btn.setBounds(10, 0, 70, 30);

        frame.add(btn);
        JPanel pnl = new JPanel();
        pnl.add(imagePanel);
        pnl.setBounds(0, 100, 1500, 1200);
        frame.add(pnl);
        frame.revalidate();
        frame.repaint();
        frame.setVisible(true);
    }

}

Question:

I have these lines of codes that I have being trying to use to read pdf file with Apache pdfBox.

    private void readPdf(){
    try {
        File PDF_Path = new File("/home/olyjosh/Downloads/my project.pdf");
        PDDocument inputPDF = PDDocument.load(PDF_Path);
        List<PDPage> allPages = inputPDF.getDocumentCatalog().getAllPages();
        PDPage testPage = (PDPage) allPages.get(5);
        System.out.println("Number of pages "+allPages.size());

        PDFPagePanel pdfPanel = new PDFPagePanel();
        jPanel1.add(pdfPanel);
        pdfPanel.setPage(testPage);

//            this.revalidate();
        inputPDF.close();
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

I want this pdf to be displayed on swing component like jPanel but this will only display the panel with the expected content of the pdf file. However, I was able to display the pdf as image using

convertToImage = testPage.convertToImage();

Please, how do I work around this or what am I doing wrong.


Answer:

Apache PDF-Box has a mailing list where I was able to ask the same question and this was the response I got

This was removed in 2.0 because it made trouble. Obviously, it doesn't work for 1.8 either, at least for you, so why bother?

There are two ways to display, either get a BufferedImage (renderImage / renderImageWithDPI) and display that somehow (see in PDFDebugger how to do it), or renderPageToGraphics which renders to a graphics device object.

If you really want to get the source code of the deleted PDFReader application (which includes PDFPagePanel), use svn to get revision 1702125 or earlier, that should have it. But if it didn't work for you in 1.8, it won't work for you now.

The point is that swing display of PDF pages isn't part of the API, it's part of some tool (now: in PDFDebugger, previously: in PDFReader)

You need to have some understanding of awt / swing. If you don't, learn it, or hire somebody. (That's what we did, and the best is: google paid it, as part of the google summer of code)

Tilman

Question:

I have a PDF file that I converted into an image. I Was able to write on top of the image but when I tried to save the shapes/lines into the pdf, the point are not their place and the shapes are inverted.

This is related to this question and it the first part was already answered. Now the second problem was when I try to scale the image. the points are not in their places.

I found out that it is not working when the scale is changed.. I updated the code and added the Translate values to the moveTo and lineTo as a parameter and it somehow worked when the scale is on default which is 72/200f.

Thank you Tilman Hausherr for your patience..

NOTE : Hold CTRL then use mouse wheel to zoom in/out. This event can change the scale and thus messing up with the points of my shape.

package pdfwriter;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.util.Matrix;

public class SO57387803DrawShapesInPDF {

    private static class MyImagePanel extends JPanel {

        final BufferedImage image;
        //final float scale = .38f;
        final int DPI = 200;
        float scale = 72f / DPI;

        //NEW
        double affineX;
        double affineY;

        AffineTransform atg;
        Point start = new Point();
        Point end = new Point();
        boolean isNewLine = true;
        static ArrayList<Line2D> lines = new ArrayList<>();
        static PDDocument document;

        public MyImagePanel() throws IOException {
            document = PDDocument.load(new File("c:\\users\\john ebarita\\documents\\plan.pdf"));
            PDFRenderer renderer = new PDFRenderer(document);

            image = renderer.renderImageWithDPI(0, DPI, ImageType.RGB);

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    if (end != start) {
                        Line2D line = new Line2D.Float(start.x, start.y, end.x, end.y);

                        lines.add(line);
                        Point2D p = calcCoordinates(e);

                        start = new Point();
                        start.x = (int) p.getX();
                        start.y = (int) p.getY();

                        repaint();
                    }

                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    Point2D p = calcCoordinates(e);
                    end = new Point();

                    end.x = (int) p.getX();
                    end.y = (int) p.getY();
                    repaint();
                }
            });
            addMouseWheelListener(new MouseWheelListener() {
                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {

                    int rotation = e.getWheelRotation();

                    //Zoom in/out on CTRL
                    if (e.isControlDown()) {

                        if (rotation < 0) {
                            scale -= .05;
                        } else {
                            scale += .05;
                        }
                        if (scale < .2) {
//                            IMAGE_SCALE = (float) .2;
                        } else if (scale > 4) {
                            scale = 4;
                        }
                        revalidate();
                        repaint();
                    }
                }
            });
        }

        private Point2D calcCoordinates(MouseEvent e) {
            Point p = new Point(e.getX(), e.getY());
            try {
                return atg.inverseTransform(p, null);
            } catch (NoninvertibleTransformException ex) {
                return p;
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2D = (Graphics2D) g.create();

//          double  affineX = (getWidth() - scale * image.getWidth()) / 2;
//          double affineY = (getHeight() - scale * image.getHeight()) / 2;
//          updated
            affineX = (getWidth() - scale * image.getWidth()) / 2;
            affineY = (getHeight() - scale * image.getHeight()) / 2;

            AffineTransform at = new AffineTransform();
            at.translate(affineX, affineY);
            at.scale(scale, scale);

            AffineTransform atf = g2D.getTransform();
            atf.concatenate(at);
            atg = (AffineTransform) at.clone();

            g2D.setTransform(atf);

            g2D.drawImage(image, 0, 0, this);
            try {
                g2D.drawLine(start.x, start.y, end.x, end.y);
            } catch (NullPointerException e) {

            }

            for (Line2D l : lines) {
                g2D.draw(l);
            }

            g2D.dispose();
        }

        public void save() {

            try {
                PDPage page = document.getPage(0);

                PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);
                contentStream.transform(Matrix.getRotateInstance(Math.toRadians(270), 0, page.getMediaBox().getHeight()));
                for (Line2D l : lines) {
                    Point2D p1 = new Point2D.Double(l.getX1(), l.getY1());
                    Point2D p2 = new Point2D.Double(l.getX2(), l.getY2());

                    p1 = atg.transform(p1, null);
                    p2 = atg.transform(p2, null);

//                    contentStream.moveTo((float) (p1.getX()), page.getMediaBox().getWidth() - (float) (p1.getY() ));
//                    contentStream.lineTo((float) (p2.getX()), page.getMediaBox().getWidth() - (float) (p2.getY() ));
                    //UPATED
                    contentStream.moveTo((float) (p1.getX() - affineX), page.getMediaBox().getWidth() - (float) (p1.getY() - affineY));
                    contentStream.lineTo((float) (p2.getX() - affineX), page.getMediaBox().getWidth() - (float) (p2.getY() - affineY));

                    contentStream.stroke();
                }

                contentStream.close();

                document.save(new File("c:\\users\\john ebarita\\documents\\saved.pdf"));
                document.close();
                System.out.println("file saved");
            } catch (IOException ex) {
//                Logger.getLogger(SO57387803DrawShapesInPDF.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }

        }

        @Override
        public Dimension getPreferredSize() {
            int width = (int) (scale * image.getWidth());
            int height = (int) (scale * image.getHeight());
            return new Dimension(width, height);
        }
    }

    public static void main(String[] args) {

//        System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");
        JFrame frame = new JFrame("PDF");
        frame.setSize(1500, 1200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        // MyImagePanel imagePanel = null;
        MyImagePanel imagePanel;
        try {
            imagePanel = new MyImagePanel();
        } catch (IOException ex) {
            ex.printStackTrace();
//            Logger.getLogger(SO57387803DrawShapesInPDF.class
//                    .getName()).log(Level.SEVERE, null, ex);
            return; // or there would be an uninitialized variable
        }

        JButton btn = new JButton("Save");

        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                imagePanel.save();
                //MyImagePanel.save();
            }
        });

        btn.setBounds(10, 0, 70, 30);

        frame.add(btn);
        JPanel pnl = new JPanel();
        pnl.add(imagePanel);
        pnl.setBounds(0, 100, 1500, 1200);
        frame.add(pnl);
        frame.revalidate();
        frame.repaint();
        frame.setVisible(true);
    }

}

Answer:

After a number of trial and error I think I got the answer to my problem with the scale and points.

I started off with 72/200f scale.So what I did was I made that the did was after transforming the points I divide with the currentScale/firstScale, then divide it to the transformed points;

Thank you Tilman Hausherr for the helping me.

  p1 = atg.transform(p1, null);
  p2 = atg.transform(p2, null);

 contentStream.moveTo((float) (p1.getX() / (scale / .36)), (float) page.getMediaBox().getWidth() - p1.getY() / (scale / .36)));
 contentStream.lineTo((float) (p2.getX() / (scale / .36)), (float) (page.getMediaBox().getWidth() - p2.getY() / (scale / .36)));

Full Code;

package pdfwriter;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.util.Matrix;

public class SO57387803DrawShapesInPDF {

    private static class MyImagePanel extends JPanel {

        final BufferedImage image;
        //final float scale = .38f;
        final int DPI = 200;
        float scale = 72f / DPI;

        //NEW
        double affineX;
        double affineY;

        AffineTransform atg;
        Point start = new Point();
        Point end = new Point();
        boolean isNewLine = true;
        static ArrayList<Line2D> lines = new ArrayList<>();
        static PDDocument document;

        public MyImagePanel() throws IOException {
            document = PDDocument.load(new File("plan.pdf"));
            PDFRenderer renderer = new PDFRenderer(document);

            image = renderer.renderImageWithDPI(0, DPI, ImageType.RGB);

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    if (end != start) {
                        Line2D line = new Line2D.Float(start.x, start.y, end.x, end.y);

                        lines.add(line);
                        Point2D p = calcCoordinates(e);

                        start = new Point();
                        start.x = (int) p.getX();
                        start.y = (int) p.getY();

                        repaint();
                    }

                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    Point2D p = calcCoordinates(e);
                    end = new Point();

                    end.x = (int) p.getX();
                    end.y = (int) p.getY();
                    repaint();
                }
            });
            addMouseWheelListener(new MouseWheelListener() {
                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {

                    int rotation = e.getWheelRotation();

                    //Zoom in/out on CTRL
                    if (e.isControlDown()) {

                        if (rotation < 0) {
                            scale -= .05;
                        } else {
                            scale += .05;
                        }
                        if (scale < .2) {
                            scale = .2f;
                        } else if (scale > 4) {
                            scale = 4;
                        }
                        revalidate();
                        repaint();
                    }
                }
            });
        }

        private Point2D calcCoordinates(MouseEvent e) {
            Point p = new Point(e.getX(), e.getY());
            try {
                return atg.inverseTransform(p, null);
            } catch (NoninvertibleTransformException ex) {
                return p;
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2D = (Graphics2D) g.create();

            //          double  affineX = (getWidth() - scale * image.getWidth()) / 2;
            //          double affineY = (getHeight() - scale * image.getHeight()) / 2;
            //          updated
            affineX = (getWidth() - scale * image.getWidth()) / 2;
            affineY = (getHeight() - scale * image.getHeight()) / 2;

            AffineTransform at = new AffineTransform();
            at.translate(affineX, affineY);
            at.scale(scale, scale);

            AffineTransform atf = g2D.getTransform();
            atf.concatenate(at);
            atg = (AffineTransform) at.clone();

            g2D.setTransform(atf);
            g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2D.drawImage(image, 0, 0, this);
            try {
                g2D.drawLine(start.x, start.y, end.x, end.y);
            } catch (NullPointerException e) {

            }

            for (Line2D l : lines) {
                g2D.draw(l);
            }

            g2D.dispose();
        }

        public void save() {

            try {
                PDPage page = document.getPage(0);

                PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);
                contentStream.transform(Matrix.getRotateInstance(Math.toRadians(270), 0, page.getMediaBox().getHeight()));
                for (Line2D l : lines) {
                    Point2D p1 = new Point((int) l.getX1(), (int) l.getY1());
                    Point2D p2 = new Point((int) l.getX2(), (int) l.getY2());

                    p1 = atg.transform(p1, null);
                    p2 = atg.transform(p2, null);

                    //UPATED
                    System.out.println("Points");
                    System.out.println(p1);
                    System.out.println(p2);
                    System.out.println("Scale " + scale);

                    //0.36 is the default scale or 72/200f 
                    contentStream.moveTo((float) (p1.getX() / (scale / .36)), (float) (page.getMediaBox().getWidth() - p1.getY() / (scale / .36)));

                    contentStream.lineTo((float) (p2.getX() / (scale / .36)), (float) (page.getMediaBox().getWidth() - p2.getY() / (scale / .36)));

                    contentStream.stroke();
                }

                contentStream.close();

                document.save(new File("c:\\users\\john ebarita\\documents\\saved.pdf"));
                document.close();
                System.out.println("file saved");
            } catch (IOException ex) {
                //                Logger.getLogger(SO57387803DrawShapesInPDF.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }

        }

        @Override
        public Dimension getPreferredSize() {
            int width = (int) (scale * image.getWidth());
            int height = (int) (scale * image.getHeight());
            return new Dimension(width, height);
        }
    }

    public static void main(String[] args) {

        //        System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");
        JFrame frame = new JFrame("PDF");
        frame.setSize(1500, 1200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        // MyImagePanel imagePanel = null;
        MyImagePanel imagePanel;
        try {
            imagePanel = new MyImagePanel();
        } catch (IOException ex) {
            ex.printStackTrace();
            //            Logger.getLogger(SO57387803DrawShapesInPDF.class
            //                    .getName()).log(Level.SEVERE, null, ex);
            return; // or there would be an uninitialized variable
        }

        JButton btn = new JButton("Save");

        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                imagePanel.save();
                //MyImagePanel.save();
            }
        });

        btn.setBounds(10, 0, 70, 30);

        frame.add(btn);
        JPanel pnl = new JPanel();
        pnl.add(imagePanel);
        pnl.setBounds(0, 100, 1500, 1200);
        frame.add(pnl);
        frame.revalidate();
        frame.repaint();
        frame.setVisible(true);
    }

}