iText操作PDF

using (FileStream fs = new FileStream(tempPdfFilePath, FileMode.Create))
{


Document document = new Document(PageSize.A4, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
writer.InitialLeading = 20;
document.Open();

//A4纸张分成两列打印

PdfPTable table = new PdfPTable(2);
table.TotalWidth = 575f;
table.LockedWidth = true;

//两列的比例
float[] widths = new float[] { 1.0f, 1.0f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;

var cell=CreateCell("测试内容", 2, ITextSharpHelper.GetChineseFont(8, FontStyle.NORMAL, FontFamily.宋体, FontColor.BLACK), 0, 13);

table.AddCell(cell);

document.Add(table);
document.Close();

fs.Close();
}

private PdfPCell CreateCell(string context, int colSpan, iTextSharp.text.Font font, int horizontalAlignment = 0, int minimumHeight = 9)
{
Phrase phrase = new Phrase();
//®
if (context.IndexOf("®") != -1)
{
phrase.Font = font;
Chunk c1 = new Chunk(context.Substring(0, context.IndexOf("®")), font);
c1.SetUnderline(0.6f, -3f);

Chunk subscript = new Chunk("®", font);
subscript.SetTextRise(2f);
subscript.SetUnderline(0.6f, -3f);

Chunk c2 = new Chunk(context.Substring(context.IndexOf("®") + 1, context.Length - context.IndexOf("®") - 1), font);
c2.SetUnderline(0.6f, -3f);

phrase.Add(c1);
phrase.Add(subscript);
phrase.Add(c2);
}
else
{
phrase = new Phrase(context, font);
}
PdfPCell cell = new PdfPCell(phrase);
cell.Border = 0;
cell.Colspan = colSpan;
cell.PaddingRight = 0f;
cell.MinimumHeight = minimumHeight;
// cell.SetLeading( = 20.0f;
cell.HorizontalAlignment = horizontalAlignment;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
return cell;
}

//插入图片

private PdfPCell CreateImgCell( int colSpan, int rowSpan)
{
//照片

iTextSharp.text.Image image = null;
string photoPath ="图片路径";

if (File.Exists(photoPath))
{
try
{
image = iTextSharp.text.Image.GetInstance(photoPath);
}
catch (Exception ex)
{
ex._Log();
System.Drawing.Bitmap image1 = new System.Drawing.Bitmap(100, 100);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image1);
System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
g.DrawString("读取照片失败", new System.Drawing.Font("宋体", 10, System.Drawing.FontStyle.Regular), b, 2, 30);
image = Image.GetInstance(image1, BaseColor.WHITE);
}
}
else
{
string noPhoto = Path.Combine(InitInfo.Config_WebRunPath, "Images\NoPhoto.jpg");
image = iTextSharp.text.Image.GetInstance(noPhoto);
}
image.ScaleAbsolute(50, 60);
image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
image.IndentationLeft = 9f;
PdfPCell cellKsPhoto = new PdfPCell(image);
cellKsPhoto.Padding = 1f;
cellKsPhoto.Rowspan = rowSpan;
cellKsPhoto.Colspan = colSpan;
cellKsPhoto.BorderWidth = 0;
cellKsPhoto.HorizontalAlignment = Element.ALIGN_CENTER;
return cellKsPhoto;
}

原文地址:https://www.cnblogs.com/hobby0524/p/6734179.html