Jim*_*mmy 25 c# cell itext vertical-alignment
我试图找出如何让我的文本在PdfPCell中显示在中间.我尝试过很多不同的选择,比如:
myCell.VerticalAlignment = Element.ALIGN_MIDDLE; myCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; myCell.VerticalAlignment = Rectangle.ALIGN_MIDDLE;
这些都不适合我.VerticalAlignment需要一个int,所以我试着创建一个循环,看看我是否能找到正确的数字,但是所有东西都只是左下方对齐..
Document myDocument = new Document(PageSize.A4);
PdfWriter myPdfWriter = PdfWriter.GetInstance(myDocument, new FileStream(strPDFFilePath, FileMode.Create));
myDocument.Open();
myDocument.NewPage();
PdfContentByte myPdfContentByte = myPdfWriter.DirectContent;
PdfPCell myCell;
Paragraph myParagraph;
PdfPTable myTable = new PdfPTable(4);
myTable.WidthPercentage = 100;
myTable.SetWidths(new int[4] { 25, 25, 25, 25 });
myTable.DefaultCell.BorderWidth = 1;
myTable.DefaultCell.BorderColor = BaseColor.RED;
for (int i = -100; i < 100; i++)
{
myParagraph = new Paragraph(String.Format("Alignment: {0}", i));
myParagraph.Font.SetFamily("Verdana");
myParagraph.Font.SetColor(72, 72, 72);
myParagraph.Font.Size = 11;
myCell = new PdfPCell();
myCell.AddElement(myParagraph);
myCell.HorizontalAlignment = i;
myCell.VerticalAlignment = i;
myTable.AddCell(myCell);
}
myDocument.Add(myTable);
myDocument.Add(new Chunk(String.Empty));
myDocument.Close();
Run Code Online (Sandbox Code Playgroud)
Jay*_*ggs 36
我认为您遇到的基本问题是您正在向iTextSharp Paragraph对象添加文本,然后尝试使用PdfPCell包含它的对象设置此文本的对齐方式.我不确定该PdfPCell.VerticalAlignment属性是仅用于PdfPCell文本,还是对齐Paragraph内部对象PdfPCell没有任何影响,您可以在测试中看到.
你还设置myCell.HorizontalAlignment并myCell.VerticalAlignment在您的索引值for循环.我认为你的意思是使用1个实例i.
无论如何,设置PdfPCell HorizontalAlignment和VerticalAlignment属性确实有效.下面是一个演示此问题的小方法.我根据你想要做的事情写得很松散; 如果它足够接近你想要做的事情,也许你可以将它作为项目的起点.
private void TestTableCreation() {
using (FileStream fs = new FileStream("TableTest.pdf", FileMode.Create)) {
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, fs);
doc.Open();
PdfPTable table = new PdfPTable(4);
for (int i = -100; i < 100; i++) {
PdfPCell cell = new PdfPCell(new Phrase(String.Format("Alignment: {0}", i)));
// Give our rows some height so we can see test vertical alignment.
cell.FixedHeight = 30.0f;
// ** Try it **
//cell.HorizontalAlignment = Element.ALIGN_LEFT;
//cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.HorizontalAlignment = Element.ALIGN_RIGHT;
cell.VerticalAlignment = Element.ALIGN_TOP;
//cell.VerticalAlignment = Element.ALIGN_MIDDLE;
//cell.VerticalAlignment = Element.ALIGN_BOTTOM;
table.AddCell(cell);
}
doc.Add(table);
doc.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
当我添加以下内容时,Jay Riggs解决方案也开始为垂直对齐工作:
cell.UseAscender = true;
http://www.afterlogic.com/mailbee-net/docs-itextsharp/html/0602b79e-ea9c-0c7d-c4b2-bc4b5f976f15.htm