Why this pageEvent cover the content of page using

2019-09-01 14:51发布

问题:

There is a PageEvent with border-line also apply background color for whole page but when this PageEvent applied the content of "createPDF" hide.

public class BlackBorder extends PdfPageEventHelper {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContent();
        Rectangle rect = document.getPageSize();
        rect.setBackgroundColor(new BaseColor(234,234,234,0));
        rect.setBorder(Rectangle.BOX);  
        rect.setBorderWidth(10);  
        rect.setBorderColor(BaseColor.BLACK); 
        rect.setUseVariableBorders(true);  
        canvas.rectangle(rect);
    }
}


//Method of createPDF.
public void createPdf(String filename) throws IOException, DocumentException {

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    BlackBorder event_border = new BlackBorder();
    writer.setPageEvent(event_border);
    document.open();
    Chunk chunk = new Chunk(String.valueOf(FileCounter)+"No"+String.valueOf(FileCounter));
    chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, 0.3f, BaseColor.CYAN);
    document.add(chunk);
    document.close();
}

If i remove rect.setBackgroundColor(new BaseColor(234,234,234,0))

the Chunk would be visible. Also i've tried Background event like:

public class Background extends PdfPageEventHelper {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContent();
        Rectangle rect = document.getPageSize();
        rect.setBackgroundColor(new BaseColor(234,234,234,0));
        canvas.rectangle(rect);
    }
}

and add

    Background event = new Background();
    writer.setPageEvent(event);

in createPdf method but app couldn't generate any PDF file!

It would be much obliged if you linked me how to have multiple PageEvent like haveing watermark, hearder-footer , background etc. I tried some of them but i think they cover each other.

Thanks..

回答1:

The rectangle covers the content because you programmed it this way.

If you want to add an opaque rectangle under the existing content, replace:

PdfContentByte canvas = writer.getDirectContent();

with:

PdfContentByte canvas = writer.getDirectContentUnder();