首页 文章

在 iTextSharp 中,我们可以设置 pdfwriter 的垂直位置吗?

提问于
浏览
4

我最近开始使用 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);

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

2 回答

  • 1

    除了 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();
    
  • 4

    好吧,我猜答案有点明显,但我一直在寻找一种特定的方法。垂直位置没有设置器,但您可以轻松地使用 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);
    

相关问题