iTextSharp AddText导致'此页存在错误'
本文关键字:存在 错误 iTextSharp AddText 导致 | 更新日期: 2023-09-27 18:01:58
生成的PDF文档得到"此页存在错误"。在acrobatadobereader中打开时。你知道为什么会这样吗?在我今天试用的旧版本iTextSharp和5.1.1版本中都发生了这种情况。
测试代码:
static void PDFErrorOnPage()
{
Document document = new Document(PageSize.LETTER);
float fMarginLeft = 15.822f; // 0.21975 inch
float fMarginRight = 15.822f; // 0.21975 inch
float fMarginTop = 36.0f; // 0.5 inch
float fMarginBottom = 36.0f; // 0.5 inch
float fLabelSpacingHorizontal = 10.08f;
float fLabelWidth = 186.732f;
float fLabelHeight = 72.0f;
float fLabelPadding = 5.0f;
float fLabelPaddingLeft = 20.0f;
float fLabelPaddingBottom = 5.0f;
float fLabelPaddingTop = 0.0f;
int nRow = 0;
int nCol = -1;
bool bDebug = true;
try
{
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 8, Font.NORMAL, BaseColor.BLACK);
Font fontBold = new Font(bf, 8, Font.BOLD, BaseColor.BLACK);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("d:''tempjunk''test.pdf", FileMode.Create));
document.SetMargins(fMarginLeft, fMarginRight, fMarginTop, fMarginBottom);
document.Open();
PdfContentByte cb = writer.DirectContent;
for (int i = 0; i < 26; i++)
{
nCol++;
if (nCol > 2)
{
nCol = 0;
nRow++;
}
if (nRow > 9)
{
nRow = 0;
document.NewPage();
Console.WriteLine("document.NewPage()");
}
float fLabelBottomLeftX = fMarginLeft + (nCol * fLabelSpacingHorizontal) + (nCol * fLabelWidth);
float fLabelBottomLeftY = fMarginBottom + ((9 - nRow) * fLabelHeight);
if (bDebug)
{
cb.SetRGBColorStroke(0x00, 0x00, 0xFF);
cb.Rectangle(fLabelBottomLeftX, fLabelBottomLeftY, fLabelWidth, fLabelHeight);
cb.Stroke();
}
cb.BeginText();
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(
fLabelBottomLeftX + fLabelPaddingLeft,
fLabelBottomLeftY + fLabelPaddingBottom,
fLabelBottomLeftX + fLabelWidth - (fLabelPaddingLeft + fLabelPadding),
fLabelBottomLeftY + fLabelHeight - (fLabelPaddingBottom + fLabelPaddingTop),
12.0f,
PdfContentByte.ALIGN_LEFT);
ct.AddText(new Chunk("One'nTwo'nThree'nFour'nFive", font));
ct.Go();
cb.EndText();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + " " + ex.StackTrace);
}
finally
{
if (document != null)
document.Close();
}
}
您需要移动BeginText和EndText方法,以便它们只适用于您的文本。以下内容适合我:
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(
fLabelBottomLeftX + fLabelPaddingLeft,
fLabelBottomLeftY + fLabelPaddingBottom,
fLabelBottomLeftX + fLabelWidth - (fLabelPaddingLeft + fLabelPadding),
fLabelBottomLeftY + fLabelHeight - (fLabelPaddingBottom + fLabelPaddingTop),
12.0f,
PdfContentByte.ALIGN_LEFT);
cb.BeginText();
ct.AddText(new Chunk("One'nTwo'nThree'nFour'nFive", font));
cb.EndText();
ct.Go();