Itextsharp:如何在页面中间放置文本

时间:2013-06-13 12:33:03

标签: c# itextsharp

我正在使用以下代码创建“标题”页面。

public static byte[] CreatePageHeader(List<string> texts) {
        var stream = new MemoryStream();
        Document doc = null;

        try {
            doc = new Document();
            PdfWriter.GetInstance(doc, stream);
            doc.SetMargins(50, 50, 50, 50);
            doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height));
            Font font = new Font(Font.FontFamily.HELVETICA, 10f, Font.NORMAL);
            doc.Open();

            Paragraph para = null;
            foreach (string text in texts) {
                para = new Paragraph(text, font);
                doc.Add(para);
            }

        } catch (Exception ex) {
            throw ex;
        } finally {
            doc.Close();
        }

        return stream.ToArray();
    }

这样可以正常工作,但它会在页面顶部显示文本。 但我希望它在页面中间。

请如何修改此代码呢?

1 个答案:

答案 0 :(得分:7)

我只需要一行,单列表。这些类型的物体支持设置固定的宽度/高度,这使您可以“居中”。的东西。

var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, fs)) {
            doc.Open();

            //Create a single column table
            var t = new PdfPTable(1);

            //Tell it to fill the page horizontally
            t.WidthPercentage = 100;

            //Create a single cell
            var c = new PdfPCell();

            //Tell the cell to vertically align in the middle
            c.VerticalAlignment = Element.ALIGN_MIDDLE;

            //Tell the cell to fill the page vertically
            c.MinimumHeight = doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin);

            //Create a test paragraph
            var p = new Paragraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam iaculis sem diam, quis accumsan ipsum venenatis ac. Pellentesque nec gravida tortor. Suspendisse dapibus quis quam sed sollicitudin.");

            //Add it a couple of times
            c.AddElement(p);
            c.AddElement(p);

            //Add the cell to the paragraph
            t.AddCell(c);

            //Add the table to the document
            doc.Add(t);
            doc.Close();
        }
    }
}