iTextSharp一切正常,但在打开pdf文档时出现奇怪的错误

时间:2010-04-29 16:16:37

标签: c# .net asp.net itextsharp

我正在使用iTextSharp动态创建我的PDF文档。 一切正常,我在代码中没有错误;但是,当我打开创建的PDF时,它会给我一个错误,说文档将无法正确显示,因为它包含错误。

以下是给我一个问题的代码:

public class pdfevents : PdfPageEventHelper
{
    public override void OnEndPage(PdfWriter writer, Document document)
    {
        base.OnEndPage(writer, document);
        PdfContentByte cb = writer.DirectContent;
        cb.BeginText();

        cb.SetTextMatrix(20, document.GetBottom(-30));
        BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.SetFontAndSize(bf, 10);

        //thats is the piece of code that makes problems
        //if i remove it then document displays without error
        cb.MoveTo(15F, document.GetBottom(-15));
        cb.SetLineWidth(0.5F);
        cb.LineTo(document.GetRight(0), document.GetBottom(-15));
        cb.Stroke();

        cb.ShowText(DateTime.Now.ToLongDateString());

        int n = writer.PageNumber;
        cb.SetTextMatrix(document.GetRight(20), document.GetBottom(-30));
        cb.ShowText(" - " + n + " - ");

        cb.EndText();
    }
}

如果我删除以下行:

//thats is the piece of code that makes problems
            //if i remove it then document displays without error
            cb.MoveTo(15F, document.GetBottom(-15));
            cb.SetLineWidth(0.5F);
            cb.LineTo(document.GetRight(0), document.GetBottom(-15));

然后我没有错误打开生成的PDF,否则我可以打开PDF并查看文档及其内容,包括该行。但是,然后我得到错误生成文档的错误。

有人可以告诉我出了什么问题吗?

提前致谢。                 cb.Stroke();

1 个答案:

答案 0 :(得分:0)

在玩了很长时间(很长一段时间)之后,我找到了一个解决方法,现在文档不仅显示内容(如之前显示的那样),而且没有给出错误信息。

我仍然不明白为什么以及这个解决方案如何运作而之前的解决方案没有,但以防万一有人会需要它或者会遇到类似的问题。

而不是:

PdfContentByte cb = writer.DirectContent;
        cb.BeginText();

        cb.SetTextMatrix(20, document.GetBottom(-30));
        BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.SetFontAndSize(bf, 10);

        //thats is the piece of code that makes problems
        //if i remove it then document displays without error
        cb.MoveTo(15F, document.GetBottom(-15));
        cb.SetLineWidth(0.5F);
        cb.LineTo(document.GetRight(0), document.GetBottom(-15));
        cb.Stroke();

我用字体代码更改了绘制线的代码位置。

base.OnEndPage(writer, document);
        PdfContentByte cb = writer.DirectContent;


        ////making a line
        cb.MoveTo(15F, document.GetBottom(-15));
        cb.SetLineWidth(0.5F);
        cb.LineTo(document.GetRight(-10), document.GetBottom(-15));
        cb.Stroke();

 cb.BeginText();

            cb.SetTextMatrix(20, document.GetBottom(-30));
            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252,  BaseFont.NOT_EMBEDDED);
            cb.SetFontAndSize(bf, 10);