代码之家  ›  专栏  ›  技术社区  ›  Pandincus

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

  •  4
  • Pandincus  · 技术社区  · 16 年前

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

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

    那么,有没有办法用手来确定作者的位置?谢谢!

    2 回复  |  直到 16 年前
        1
  •  4
  •   Pandincus    16 年前

    好吧,我想答案是有点明显,但我在寻找一个具体的方法。垂直位置没有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);
    
        2
  •  1
  •   BlueRaja - Danny Pflughoeft    16 年前

    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();
    
    推荐文章