iTextSharp:展平表格单元格中的字段会向上移动文本

时间:2014-08-19 23:42:44

标签: c# pdf itextsharp

我在使用表格单元格中生成的字段展平时遇到问题。我已经创建了一个示例项目来说明问题。

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");
    }

生成的这个unflattened pdf看起来像this。正如您所看到的,该领域应该是它应有的位置。然而,展平的pdf看起来像this。该字段的文本已被移动了一个显着的数量。

posted the flattened pdf所以如果需要,有人可以查看pdf语言。

我知道这是一个利基问题,但希望有人可以帮助我。

EDIT1:回应Bruno的评论,我正在使用从Nuget下载的iTextsharp 5.5.2,可以找到unflattened pdf here.

EDIT2:更新了SO链接以指向正确的问题。以下是我之前提出的与此问题相关的两个问题:FirstSecond

1 个答案:

答案 0 :(得分:0)

iText的Java版本不包含此问题。这是一个Java - > C#移植问题。我们会照顾好。