4

我正在使用下面的代码来创建标题页。

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();
    }

这工作正常,但它在页面顶部显示文本。但我想要它在页面的中间。

请问我该如何修改这个代码呢?

4

1 回答 1

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();
        }
    }
}
于 2013-06-13T13:01:40.903 回答