简体   繁体   English

itext字体颜色在第一页变暗

[英]itext font color gets darker in first page

I'm using iText 2.1.7,i'm adding header and footer at absolute position using writer.getDirectcontent() method.All is working fine except the fonts in first page gets darker than second pages. 我正在使用iText 2.1.7,我使用writer.getDirectcontent()方法在绝对位置添加页眉和页脚。除了第一页中的字体比第二页更暗以外,所有工作正常。

Note the Header and Footer in First and second pages 请注意第一页和第二页中的页眉和页脚

在此输入图像描述

在此输入图像描述

anyhelp? anyhelp?

Here is what i did 这就是我做的

Reader stringReader = new StringReader(svgXmlDoc);

    Document document = new Document(PageSize.A4.rotate());

    ByteArrayOutputStream content = new ByteArrayOutputStream();
    try {

        PdfWriter writer = PdfWriter.getInstance(document, content);

        document.open();

        PdfService event = new PdfService();
        event.setHeader(date.toString());

        event.onOpenDocument(writer, document);
        event.onEndPage(writer, document);
        event.onCloseDocument(writer, document);
        writer.setPageEvent(event);

        Image image1 = Image.getInstance("Infinity-Loop.png");

        image1.scalePercent(35);

        PdfPTable signature = new PdfPTable(numberOfSignature);

        signature.setTotalWidth(document.getPageSize().getWidth()
                - document.leftMargin() - document.rightMargin());
        signature.setLockedWidth(true);
        signature.setWidthPercentage(100);
        signature.getDefaultCell().setFixedHeight(20);

        signature.getDefaultCell().setHorizontalAlignment(
                Element.ALIGN_RIGHT);
        for (int i = 0; i < numberOfSignature; i++) {
            PdfPCell cell = new PdfPCell(new Paragraph(
                    String.valueOf("____________")));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            signature.addCell(cell);
        }

        PdfPTable header = new PdfPTable(3);

        float[] columnWidths = {1f,2f,1f};
         header.setWidths(columnWidths);
        header.setTotalWidth(document.getPageSize().getWidth()
                - document.leftMargin() - document.rightMargin());
        header.setLockedWidth(true);
        header.setWidthPercentage(100);
         header.getDefaultCell().setPadding(15);
        header.getDefaultCell().setBorder(Rectangle.NO_BORDER);

        PdfPCell logocell = new PdfPCell(image1, false);
        logocell.setRowspan(3);
        logocell.setFixedHeight(72);
        logocell.setBorder(Rectangle.NO_BORDER);
        header.addCell(logocell);

        PdfPCell Title = new PdfPCell(new Phrase(title,
                FontFactory.getFont(FontFactory.TIMES_ROMAN, 18,
                        Font.PLAIN, new Color(0, 0, 0))));
        Title.setBorder(Rectangle.NO_BORDER);
        Title.setHorizontalAlignment(Element.ALIGN_CENTER);
        header.addCell(Title);
        header.addCell("");
        header.completeRow();
        PdfPCell SubTitle = new PdfPCell(new Phrase(subTitle));
        SubTitle.setBorder(Rectangle.NO_BORDER);
        SubTitle.setHorizontalAlignment(Element.ALIGN_CENTER);
        header.addCell(SubTitle);
        header.addCell("");
        header.completeRow();
        PdfPCell dataRange = new PdfPCell(new Phrase(
                dateRange));
        dataRange.setBorder(Rectangle.NO_BORDER);
        dataRange.setHorizontalAlignment(Element.ALIGN_CENTER);
        header.addCell(dataRange);
        header.addCell("");
        header.completeRow();
        ArrayList tmp = header.getRows(0, header.getRows().size());
        header.getRows().clear();
        header.getRows().addAll(tmp);

        int width = (int) ((int) document.getPageSize().getWidth()
                - document.leftMargin() - document.rightMargin());
        int height = 350;
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate template = cb.createTemplate(width, height);
        Graphics2D g2 = template.createGraphics(width, height);

        PrintTranscoder prm = new PrintTranscoder();
        TranscoderInput ti = new TranscoderInput(stringReader);
        prm.transcode(ti, null);

        PageFormat pg = new PageFormat();
        Paper pp = new Paper();
        pp.setSize(width, height);
        pp.setImageableArea(0, 0, width, height);
        pg.setPaper(pp);
        prm.print(g2, pg, 0);
        g2.dispose();

        ImgTemplate img = new ImgTemplate(template);
        img.setAbsolutePosition(document.left(), document.topMargin() + 100);
        document.add(img);
        signature.writeSelectedRows(0, -1, document.left(),
                document.bottom() + document.bottomMargin() * 2,
                writer.getDirectContent());

        header.writeSelectedRows(0, -1, document.left(), document.top(),
                writer.getDirectContent());
        document.newPage();

    PdfPTable statisticsTitle=new PdfPTable(1);
    statisticsTitle.setTotalWidth(document.right() - document.left());
    statisticsTitle.setWidthPercentage(100);
    PdfPCell titleCell= new PdfPCell(new Paragraph("Statistics Report"));
    titleCell.setBorder(Rectangle.NO_BORDER);
    titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    statisticsTitle.addCell(titleCell);
    statisticsTitle.writeSelectedRows(0, -1, document.left(), document.top()
            - document.topMargin() * 2 - 10, writer.getDirectContent());

        PdfPTable table;
        if(measurementType.equals("Temp")){
            table = new PdfPTable(6);
        }
        else{
            table = new PdfPTable(11);
        }
        table.setTotalWidth(document.right() - document.left());
        table.setWidthPercentage(100);
        table.setHeaderRows(1);


        PdfPCell h1 = new PdfPCell(new Paragraph("Description"));
        h1.setGrayFill(0.7f);
        h1.setRowspan(2);
        h1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        h1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(h1);

        PdfPCell h2 = new PdfPCell(new Paragraph("Temperature"));
        h2.setGrayFill(0.7f);
        h2.setColspan(5);
        h2.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(h2);

        if(measurementType.equals("TempHumi")){
            PdfPCell h3 = new PdfPCell(new Paragraph("Humidity"));
            h3.setGrayFill(0.7f);
            h3.setColspan(5);
            h3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(h3);
        }
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        PdfPCell tc1 = new PdfPCell(new Paragraph("Min"));
        tc1.setGrayFill(0.7f);
        tc1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(tc1);

        PdfPCell tc2 = new PdfPCell(new Paragraph("Max"));
        tc2.setGrayFill(0.7f);
        tc2.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(tc2);

        PdfPCell tc3 = new PdfPCell(new Paragraph("Avg"));
        tc3.setGrayFill(0.7f);
        tc3.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(tc3);

        PdfPCell tc4 = new PdfPCell(new Paragraph("Std"));
        tc4.setGrayFill(0.7f);
        tc4.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(tc4);

        PdfPCell tc5 = new PdfPCell(new Paragraph("Mkt"));
        tc5.setGrayFill(0.7f);
        tc5.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(tc5);

        if(measurementType.equals("TempHumi")){
        PdfPCell hc1 = new PdfPCell(new Paragraph("Min"));
        hc1.setGrayFill(0.7f);
        hc1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(hc1);

        PdfPCell hc2 = new PdfPCell(new Paragraph("Max"));
        hc2.setGrayFill(0.7f);
        hc2.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(hc2);

        PdfPCell hc3 = new PdfPCell(new Paragraph("Avg"));
        hc3.setGrayFill(0.7f);
        hc3.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(hc3);

        PdfPCell hc4 = new PdfPCell(new Paragraph("Std"));
        hc4.setGrayFill(0.7f);
        hc4.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(hc4);

        PdfPCell hc5 = new PdfPCell(new Paragraph("Mkt"));
        hc5.setGrayFill(0.7f);
        hc5.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(hc5);
        }



        ArrayList tmpTable = table.getRows(0, table.getRows().size());
        table.getRows().clear();
        table.getRows().addAll(tmpTable);

        JsonObject listloggerdatastatistics = ReportService
                .getStatisticsDetails(serialnumberlist);

        System.out.println("Json "+listloggerdatastatistics.get("Sensormodellist"));

        for (int row = 0; row < listloggerdatastatistics.get("Sensormodellist").getAsJsonArray().size(); row++) {
            JsonObject jsonobj=listloggerdatastatistics.get("Sensormodellist").getAsJsonArray().get(row).getAsJsonObject();
            if (row > 20 && row % 21 == 0) {

                table.completeRow();

                table.writeSelectedRows(0, 22, document.left(),
                        document.top() - document.topMargin() * 2 - 10,
                        writer.getDirectContent());
                table.deleteBodyRows();
                table.setSkipFirstHeader(true);
                signature.writeSelectedRows(0, -1, document.left(),
                        document.bottom() + document.bottomMargin() * 3,
                        writer.getDirectContent());

                header.writeSelectedRows(0, -1, document.left(),
                        document.top(), writer.getDirectContent());

                document.newPage();
            }



            table.addCell(jsonobj.get("Modeltype").getAsString());
            table.addCell(""+jsonobj.get("Mintemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
            table.addCell(""+jsonobj.get("Maxtemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
            table.addCell(""+jsonobj.get("Avgtemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
            table.addCell(""+jsonobj.get("Stdtemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
            table.addCell(""+jsonobj.get("Mkttemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
            if(measurementType.equals("TempHumi")){
                table.addCell(""+jsonobj.get("Minhumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
                table.addCell(""+jsonobj.get("Maxhumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
                table.addCell(""+jsonobj.get("Avghumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
                table.addCell(""+jsonobj.get("Stdhumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
                table.addCell("-");
            }


        }

        table.completeRow();
        table.writeSelectedRows(0, -1, document.left(), document.top()
                - document.topMargin() * 3 - 10, writer.getDirectContent());
        signature.writeSelectedRows(0, -1, document.left(),
                document.bottom() + document.bottomMargin() * 2,
                writer.getDirectContent());
        header.writeSelectedRows(0, -1, document.left(), document.top(),
                writer.getDirectContent());


    } catch (DocumentException e) {
        System.err.println(e);
    }
    document.close();
    content.close();

I'm constructing graph image from SVG and table data are populated from database 我正在从SVG构建图形图像,表格数据从数据库中填充

Event handlers for adding footer with page X of Y 用于添加页脚X的页脚的事件处理程序

public class PdfService extends PdfPageEventHelper {
/** The header text. */
String header;
/** The template with the total number of pages. */
PdfTemplate total;

/**
 * Fills out the total number of pages before the document is closed.
 * 
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
 *      com.itextpdf.text.Document)
 */
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
    total.reset();
    ColumnText
            .showTextAligned(total, Element.ALIGN_LEFT,
                    new Phrase(String.valueOf(writer.getPageNumber() - 1)),
                    2, 2, 0);

}

/**
 * Adds a header to every page
 * 
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
 *      com.itextpdf.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {

    PdfPTable table = new PdfPTable(4);
    try {
        table.setWidths(new float[] { (float) (2.25), (float) (1.5), 11, 13 });
        table.setTotalWidth(document.getPageSize().getWidth()
                - document.leftMargin() - document.rightMargin());
        table.setLockedWidth(true);
        table.setWidthPercentage(100);
        table.getDefaultCell().setFixedHeight(20);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);

        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(String.format("Page %d of", writer.getPageNumber()));
        Image img = Image.getInstance(total);
        Chunk conte = new Chunk(img, 0, 0);
        Phrase chunk = new Phrase(conte);

        PdfPCell cell = new PdfPCell(chunk);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);

        table.addCell(cell);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell("SuperAdmin");
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(header);
        table.writeSelectedRows(0, -1, document.leftMargin(),
                document.bottom(), writer.getDirectContent());

    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    }
}

/**
 * Creates the PdfTemplate that will hold the total number of pages.
 * 
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
 *      com.itextpdf.text.Document)
 */
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    total = writer.getDirectContent().createTemplate(15, 14);
    // total.setBoundingBox(new Rectangle(-1, 6, 20, 20));
}

/**
 * Allows us to change the content of the header.
 * 
 * @param header
 *            The new header String
 */
public void setHeader(String header) {
    this.header = header;
}
}

In old days, when people had one font program for one regular font and no separate font file for a bold font, people found ways to work around this problem, and Adobe Reader was adapted to make this workaround work. 在过去,当人们有一个常规字体的字体程序而没有单独的字体文件用于粗体字体时,人们找到了解决此问题的方法,并且Adobe Reader已经过调整以使这种解决方法起作用。

The workaround consists of writing the same content twice (or more) at the same position. 解决方法包括在同一位置编写两次(或更多)相同的内容。 When you add "Page 1 of 2" once, the font is presented as a regular font. 当您添加“第1页,共2页”一次时,字体将显示为常规字体。 When you add it twice, the font is presented as a bold font. 当您添加两次时,字体将显示为粗体字体。

This is what happens in your case: you are adding the footer twice. 在您的情况下会发生这种情况:您要添加两次页脚。 This is wrong: 这是错的:

document.open();
PdfService event = new PdfService();
event.setHeader(date.toString());
event.onOpenDocument(writer, document);
event.onEndPage(writer, document);
event.onCloseDocument(writer, document);
writer.setPageEvent(event);

You invoke event.onEndPage() yourself, adding the footer a first time. 您自己调用event.onEndPage() ,第一次添加页脚。 When a page is finished, iText calls the onEndPage() method a second time, adding the footer once more, resulting in a bold font. 页面完成后,iText onEndPage()调用onEndPage()方法,再次添加页脚,生成粗体字。

You should adapt your code like this: 您应该像这样调整您的代码:

PdfService event = new PdfService();
event.setHeader(date.toString());
writer.setPageEvent(event);
document.open();

You should declare the event to the PdfWriter instance before opening the document. 您应该打开文档之前将事件声明到PdfWriter实例。 You should not call the onOpenDocument() , onEndPage() and onCloseDocument() methods yourself! 你不应该自己调用onOpenDocument()onEndPage()onCloseDocument()方法! They are called internally by iText. 它们由iText在内部调用。

You should also upgrade to the latest version for the reasons explained on the FAQ . 您还应该升级到最新版本,原因在FAQ上有解释。 Using Open Source and contributing nothing in return is unwise. 使用开源并且没有任何回报是不明智的。 Supporting your open source communities isn't charity, it's good business. 支持您的开源社区不是慈善事业,这是一件好事。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM