2010-05-21 104 views
4

我最近开始使用iTextSharp从数据生成PDF报告。它工作得非常好。在iTextSharp中,我们可以设置pdfwriter的垂直位置吗?

在一个特定的报告中,我需要一个部分始终出现在页面的底部。我使用的是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); 

那么,有什么办法可以手动设置作者的位置吗?谢谢!

回答

4

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

是的,我们能做到这一点,但这仍然不能真正改变作者的垂直位置。所以如果我添加一个新的段落,短语,块,表或其他项目,它仍然会出现在其他地方。我认为。 – Pandincus 2010-05-21 14:42:50

相关问题