OiO.lk Blog java is there a way to remove only QR codes from each page of a PDF using iText7
java

is there a way to remove only QR codes from each page of a PDF using iText7


I am trying to remove QR code from each page using iText7 but it is distorting every other text values and components of the page, is there a way to do it in a proper way. Below is the code I am using:

LoopStarts{

        PdfPage page = pdfDoc.getPage(i);
        PdfDictionary resources = page.getResources().getPdfObject();

        // Retrieve all image objects on the page
        PdfDictionary xObjects = resources.getAsDictionary(PdfName.XObject);
        if (xObjects != null) {
            for (PdfName name : xObjects.keySet()) {
                PdfObject obj = xObjects.get(name);
                if (obj instanceof PdfStream) {
                    PdfStream stream = (PdfStream) obj;
                    PdfImageXObject image = new PdfImageXObject(stream);

                    // Get the width and height from the image dictionary
                    float width = image.getWidth();
                    float height = image.getHeight();

                    // Check if the image dimensions match those of a typical QR code
                    if (isLikelyQRCode(width, height)) {
                        // Clear image content to effectively remove it
                        stream.clear();
                    }
                }
            }
        }
    
LoopEnds}


// Method to determine if an image matches the typical size of a QR code
`private static boolean isLikelyQRCode(float width, float height) {
    // QR codes are typically square or nearly square
    return width >= 50f && width <= 200f &&
           height >= 50f && height <= 200f &&
           Math.abs(width - height) < 10; 
}`

I tried ‘ImageRenderListener’ but couldn’t get it as expected so I am open to any better solution.



You need to sign in to view this answers

Exit mobile version