Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

android - How to draw border for whole pdf pages using iText library 5.5.2

As in title mentioned, how to draw border with "RED" color , width-stroke 5 for all generated pdf pages using iText library. I've tried some codes but got no result.

(1)

                    PdfPTable table = new PdfPTable(1);
                    table.setWidthPercentage(99);
                    table.setLockedWidth(true);

                    PdfPCell cell = new PdfPCell();
                    cell.setFixedHeight(PageSize.A4.getHeight());


                    document.add(table);

(2)

                    PdfContentByte content = PdfWriter.getInstance(document, fout).getDirectContent();
                    Rectangle pageRect = document.getPageSize();

                    pageRect.setLeft(pageRect.getLeft() + 10);
                    pageRect.setRight(pageRect.getRight() - 10);
                    pageRect.setTop(pageRect.getTop() - 10);
                    pageRect.setBottom(pageRect.getBottom() +10);

                    content.setColorStroke( BaseColor.BLUE);
                    content.rectangle(pageRect.getLeft(), pageRect.getBottom(), pageRect.getWidth(), pageRect.getHeight());
                    content.setLineWidth(10);
                    content.stroke();
                    content.fillStroke();

Those methods give me no result, Thanks!


Edit

I've changed my methods also thanks to Bruno Lowagie for his respond. the example worked like a charm but i couldn't fit it into my code.

Here's my code: By pressing a button, PDF file will generate at specif address. I'll add more content later but now let's stick to generating pdf file(s).

   SaveToSD = (Button)findViewById(R.id.SaveToMemoryCard_xml);
    SaveToSD.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View sssdd)
        {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ConcreteProject";
            File dir = new File(path);
            if (!dir.exists())
                dir.mkdirs();
            Log.d("PDFCreator", "PDF Path: " + path);

            // Incremental Process of Creating File(s).
            String pdfName = "SDG_Created_pdf.pdf";
            int num = 0;
            File file = new File(dir, pdfName);
            while (file.exists()) {
                num++;
                pdfName = "SDG_Created_pdf" + num + ".pdf";
                file = new File(dir, pdfName);
            }


            try {

                new ConAccept_Result().createPdf(pdfName);


            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }//End Of onClick(View sssdd).
    });

And Here is method/class definitions:

public class RedBorder extends PdfPageEventHelper {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContent();
        Rectangle rect = document.getPageSize();
        rect.setBorder(Rectangle.BOX); // left, right, top, bottom border
        rect.setBorderWidth(5); // a width of 5 user units
        rect.setBorderColor(BaseColor.RED); // a red border
        rect.setUseVariableBorders(true); // the full width will be visible
        canvas.rectangle(rect);
    }
}

public void createPdf(String stringfile) throws IOException, DocumentException {
    // step 1
    com.itextpdf.text.Document document = new com.itextpdf.text.Document();

    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(stringfile));
    RedBorder event = new RedBorder();
    writer.setPageEvent(event);
    // step 3
    document.open();
    // step 4

    Chunk chunk = new Chunk("Lovin' iText - Lovin' iText");
    chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, 0.3f, BaseColor.CYAN);
    document.add(chunk);

    // step 5
    document.close();
}

After running da app a folder as i named created but there is no PDF file !

Thanks a lot..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reading your question, it seems obvious that you need a page event. Your attempts will add a border only once whereas you probably want to add a border to each page.

Please take a look at the PageBorder example. In this example, you'll find an implementation of the PageEvents interface named RedBorder:

public class RedBorder extends PdfPageEventHelper {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContent();
        Rectangle rect = document.getPageSize();
        rect.setBorder(Rectangle.BOX); // left, right, top, bottom border
        rect.setBorderWidth(5); // a width of 5 user units
        rect.setBorderColor(BaseColor.RED); // a red border
        rect.setUseVariableBorders(true); // the full width will be visible
        canvas.rectangle(rect);
    }
}

The onEndPage() method is triggered automatically, every time a page ends (do not use theonStartPage() method to add content).

In the implementation of this method, we ask the document object for its current page size. Note that the document instance passed to the event is of type PdfDocument. It is not the same document as used in the createPdf() method.

We adapt the rectangle to our needs. We set the border to BOX meaning we want to add a border to the left, right, top and bottom. We define the width of the border (in this case 5 user units) and we define the color.

If you would stop there, a rectangle with a border of 5 user units would be drawn, but you would only see lines of 2.5 user units because the other half of the 5 user units would be outside the visible area of the page.

You can avoid this by using a width of 10 user units, or by setting the variable borders flag to true.

Now all we have to do is to pass the rect object to the rectangle() method. This method is different from the method with the same name you have used in the sense that it also strokes the rectangle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...