【发布时间】:2014-08-19 23:42:43
【问题描述】:
我在扁平化表格单元格中生成的字段时遇到问题。我创建了一个示例项目来说明这个问题。
private static void dummyFunction2()
{
// Create a PDF with a TextBox in a table cell
//Get the font ready
BaseFont bfHelvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);
var helvetica12 = new Font(bfHelvetica, 12, Font.NORMAL, BaseColor.BLACK);
//Create the document and filestream
var doc = new Document(PageSize.LETTER, 18f, 18f, 18f, 18f);
var fs = new FileStream("TextBoxInTableCell.pdf", FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
//Create the table
doc.Open();
var myTable = new PdfPTable(1);
myTable.TotalWidth = 568f;
myTable.LockedWidth = true;
myTable.HorizontalAlignment = 0;
//Create the textfield that will sit on a cell in the table
var tf = new TextField(writer, new Rectangle(67, 585, 140, 800), "cellTextBox");
tf.Text = "test";
//Create the table cell
var tbCell = new PdfPCell(new Phrase(" ", helvetica12));
//Use fieldpositioningevents to make the field appear on top of the cell
var events =
new FieldPositioningEvents(writer, tf.GetTextField());
tbCell.CellEvent = events;
//Add the cell to the table
myTable.AddCell(tbCell);
PdfContentByte cb = writer.DirectContent;
//Write out the table to the middle of the document
myTable.WriteSelectedRows(0, -1, 0, -1, 0, 400, cb);
doc.Close();
fs.Close();
//Open back up the document so that we can set GenerateAppearances to false.
//This solution proposed and accepted at https://stackoverflow.com/questions/25169342/itextsharp-fields-generated-in-a-table-not-shown-in-adobe-reader
var reader2 = new PdfReader("TextBoxInTableCell.pdf");
var stamper2 = new PdfStamper(reader2, new FileStream("tempdoc.pdf", FileMode.Create));
stamper2.AcroFields.GenerateAppearances = false;
stamper2.Close();
reader2.Close();
Process.Start("tempdoc.pdf");
//Open the pdf back up
var reader = new PdfReader("tempdoc.pdf");
var stamper = new PdfStamper(reader, new FileStream("tempdoc.pdf" + "1.pdf", FileMode.Create));
//Flatten the form
stamper.FormFlattening = true;
//Close everything
stamper.Close();
reader.Close();
Process.Start("tempdoc.pdf" + "1.pdf");
}
生成的这个未展平的 pdf 看起来像 。如您所见,该字段位于应有的位置。然而,扁平化的 pdf 看起来像 。该字段的文本已明显移动。
我有posted the flattened pdf,以便有人可以在需要时查看 pdf 语言。
我知道这是一个小众问题,但希望有人可以帮助我。
EDIT1:针对 Bruno 的评论,我正在使用从 Nuget 下载的 iTextsharp 5.5.2,可以在here.找到未扁平化的 pdf。
【问题讨论】:
-
如果出现以下情况会有所帮助:(1) 您告诉我们您使用的是哪个版本的 iTextSharp(它看起来像是几年前修复的错误;我们需要知道是否存在回归)和(2) 如果您可以共享未拼合的 PDF,以便我们可以尝试重现问题。
-
@BrunoLowagie 嘿布鲁诺。我正在使用 5.5.2,从 nuget 全新下载。未展平的 pdf 可在此处找到:dropbox.com/s/60ric60quj0b063/tempdoc.pdf
-
为什么将
GenerateAppearances设置为false?我查看了stackoverflow.com/questions/25190470/…,但找不到对GenerateAppearances更改的任何引用。 -
@BrunoLowagie 我实际上发布了错误的链接。答案是stackoverflow.com/questions/25169342/…。另一篇文章确实提供了更好的解决方案,但它要么不起作用,要么我决定做更简单的选择。
-
@BrunoLowagie 使用其他解决方案有效。我想我只是认为另一个更简单。虽然我打算使用这个解决方案来解决我的问题,但我仍然很想知道为什么会发生这个问题。
标签: c# pdf itextsharp