【问题标题】:In iTextSharp, can we set the vertical position of the pdfwriter?在iTextSharp中,我们可以设置pdfwriter的垂直位置吗?
【发布时间】:2011-02-22 09:09:20
【问题描述】:

我最近开始使用 iTextSharp 从数据中生成 PDF 报告。效果很好。

在一个特定的报告中,我需要一个部分始终显示在页面底部。我正在使用 PdfContentByte 从底部创建一条虚线 200f:

cb.MoveTo(0f, 200f);
cb.SetLineDash(8, 4, 0);
cb.LineTo(doc.PageSize.Width, 200f);
cb.Stroke();

现在我想在该行下方插入内容。但是,(如预期的那样)PdfContentByte 方法不会更改 PdfWriter 的垂直位置。例如,新段落出现在页面的前面。

// appears wherever my last content was, NOT below the dashed line
doc.Add(new Paragraph("test", _myFont));

有什么方法可以指示 pdfwriter 我现在想将垂直位置推进到虚线下方,并继续在那里插入内容?有一个 GetVerticalPosition() 方法——如果有相应的 Setter 就好了:-)。

// Gives me the vertical position, but I can't change it
var pos = writer.GetVerticalPosition(false);

那么,有没有办法手动设置作家的位置?谢谢!

【问题讨论】:

    标签: c# .net pdf pdf-generation itextsharp


    【解决方案1】:

    好吧,我想答案有点明显,但我正在寻找一个具体的方法。垂直位置没有设置器,但您可以轻松地使用 writer.GetVerticalPosition() 和 paragraph.SpacingBefore 的组合来实现此结果。

    我的解决方案:

    cb.MoveTo(0f, 225f);
    cb.SetLineDash(8, 4, 0);
    cb.LineTo(doc.PageSize.Width, 225f);
    cb.Stroke();
    
    var pos = writer.GetVerticalPosition(false);
    
    var p = new Paragraph("test", _myFont) { SpacingBefore = pos - 225f };
    doc.add(p);
    

    【讨论】:

      【解决方案2】:

      除了 SpacingBefore,通常的做法是使用 PdfContentByte 添加文本,而不是直接添加到 Document

      // we create a writer that listens to the document
      // and directs a PDF-stream to a file
      PdfWriter writer = PdfWriter.getInstance(document, new FileStream("Chap1002.pdf", FileMode.Create));
      document.Open();
      
      // we grab the ContentByte and do some stuff with it
      PdfContentByte cb = writer.DirectContent;
      
      // we tell the ContentByte we're ready to draw text
      cb.beginText();
      
      // we draw some text on a certain position
      cb.setTextMatrix(100, 400);
      cb.showText("Text at position 100,400.");
      
      // we tell the contentByte, we've finished drawing text
      cb.endText();
      

      【讨论】:

      • 是的,我们可以这样做,但这仍然不会真正修改作者的垂直位置。因此,如果我添加新的段落、短语、块、表格或其他项目,它仍会出现在其他地方。我想。
      猜你喜欢
      • 2014-02-20
      • 2011-06-16
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      相关资源
      最近更新 更多