(Kind of solved but still appreciate better answers) Android Studio: How to identify certain special pages in a PDF file?

Tags: , ,

I am writing an app that generates Maths worksheets for school students. It will, for example, generate 2 to 5 pages of simple Maths questions and 1 to 2 pages of answers. The PDF can be saved to file and loaded again later. Then it has a print function that can print all the pages. I want to make it skip printing the answer pages.

Is it possible to automatically identify which pages are the answer pages? I can only think of a workaround by making those answer pages have special height or width but not even sure if this works. Are there any better ways to do this?


Ok, I continued the project and used the following method: when constructing the PDF, I put the word “Answer on the top left corner with a gray rectangle surrounding it drawn with drawRect(). Then before the actual printing, I used the following code inside the PrintDocumentAdapter() class to check whether the color of the pixel 0,0 is gray or not.

        public void onStart() {
            if (parcelFileDescriptor != null) {
                try {
                    pdfRenderer = new PdfRenderer(parcelFileDescriptor);
                } catch (IOException e) {
            int tempTotal = pdfRenderer.getPageCount();
            Bitmap[] tempBitmap = new Bitmap[tempTotal];
            finalTotal = tempTotal;
            for (int pageNum = 0; pageNum < tempTotal; pageNum++) {
                PdfRenderer.Page tempPage = pdfRenderer.openPage(pageNum);
                tempBitmap[pageNum] = Bitmap.createBitmap(WS_WIDTH, WS_HEIGHT, Bitmap.Config.ARGB_8888);
                tempPage.render(tempBitmap[pageNum], null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
                if (tempBitmap[pageNum].getPixel(0, 0) == Color.GRAY) {

It works fine. At least should cause no problem if the users only attempt to print PDF files constructed with my app. 😛

Please tell me if you know a better way to do this. Thanks!

Source: stackoverflow