PdfPTable cell width

2020-07-30 01:29发布

问题:

I'm using iTextSharp to create PDFs in my application. However I have to recreate a table, where I have to set the size for a very small column. Below is the picture that shows the size I want to set the column:

When the rest of the table creation all is well, I can't set this width.

Code:

PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 82.0f;
PdfPCell cell = new PdfPCell(new Phrase("Com a assinatura autógrafa, o signatário desta Auto-declaração garante ter cumprido estas condições:", fontetexto));
cell.PaddingBottom = 10f;
cell.PaddingTop = 10f;
cell.Colspan = 2;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("1. ");
table.AddCell("Os óleos e gorduras vegetais velhos fornecidos são biomassa conforme o Decreto de biomassa.");

回答1:

try with this code

PdfPTable table =  new PdfPTable(new float[] { 30f, 400f });
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
table.SetWidths(widths);


回答2:

You can do this with much less efforts if you use XmlParser rather then the normal HtmlParser

var document = new Document();
var workStream = new MemoryStream(); // or you can use fileStream also.
 PdfWriter writer = PdfWriter.GetInstance(document, workStream);
 XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, stream, Encoding.UTF8);

Check this nuget MvcRazorToPdf ,I found this better then RazorPDF



回答3:

The following code worked for me:

PdfPTable table = new PdfPTable(2);
table.TotalWidth = 500;
table.SetTotalWidth(new float[] { 30f, 400f });

PdfPCell c1 = new PdfPCell();
PdfPCell c2 = new PdfPCell();

c1.AddElement(new Phrase("first column"));
c1.AddElement(new Phrase("second column"));

table.Rows.Add(new PdfPRow(new PdfPCell[] { c1, c2 }));


回答4:

The answer from @IntellectWizard help me to reach a solution.

float[] widths = new float[] { 100f, 4000f }; // Code @IntellectWizard

gives a corrupted file, then i try:

PdfPTable table = new PdfPTable(new float[] { 30f, 400f });

This works!