一切的开始必须要有2个dll, 可以通过nuget 包xiazai, 关键字是itextsharp.
using iTextSharp.text; using iTextSharp.text.pdf;
FileStream fs = new FileStream(Server.MapPath("pdf") + "\\" + "First PDF document6.pdf", FileMode.Create); //doneDocument document = new Document(PageSize.A4, 25, 25, 30, 30); PdfWriter writer = PdfWriter.GetInstance(document, fs);document.AddAuthor("Micke Blomquist");document.AddCreator("Sample application using iTextSharp");document.AddKeywords("PDF tutorial education");document.AddSubject("Document subject - Describing the steps creating a PDF document");document.AddTitle("The document title - PDF creation using iTextSharp");document.Open();document.Add(new Paragraph(""));
以上就可以简单的在文档中找到Doc1.pdf 了,现在会记入简单的css样式。
Font arial = FontFactory.GetFont("Arial", 28, Font.BOLD, BaseColor.RED);//字体 Chunk c1 = new Chunk("A chunk represents an isolated string.", arial); c1.SetUnderline(0.5f, -1.5f);//下划线 document.Add(c1);
chunk是可以赋予很多的style,目前我只需要下划线和基本的字体,颜色。接下来是table
PdfPTable table = new PdfPTable(2); //列table.TotalWidth = 216f; //table widthtable.LockedWidth = true; //配合table widthfloat[] widths = new float[] { 3f, 2f }; //table 的行比列 table.SetWidths(widths); table.SpacingBefore = 10f; //margin-toptable.SpacingAfter = 30f; //margin-bottomtable.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right (float) PdfPCell cell = new PdfPCell(new Phrase("content"));//cell.Colspan = 1; //列cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right (text)cell.Padding = 10;//cell.Border = 1; table.AddCell(cell);table.AddCell(cell);table.AddCell(cell);table.AddCell(cell);table.AddCell(cell);table.AddCell(cell);document.Add(table);
table设计的是像html的float,首先给table知道几列,以上是2列,所以所有的cell都是左右左右的排列。最后是图片
document.Add(new Paragraph("JPG"));iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(Server.MapPath("123.jpg"));document.Add(gif);
完成了,这就是基本功了!
http://www.mikesdotnetting.com/article/80/create-pdfs-in-asp-net-getting-started-with-itextsharp