我正在使用下面的代码创建一个标题页面.
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();
}
这工作正常,但它显示页面顶部的文本.
但我希望它在页面中间.
请问如何修改此代码呢?
解决方法:
我只想一个单行的单列表.这些类型的对象支持设置固定的宽度/高度,允许您“居中”.
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();
}
}
}