這篇文章主要為大家詳細介紹了C#產生PDF檔案流的相關資料,具有一定的參考價值,感興趣的小夥伴們可以參考一下
本文執行個體為大家分享了C#產生PDF檔案流的具體代碼,供大家參考,具體內容如下
1、設定字型
static BaseFont FontBase = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); static iTextSharp.text.Font bodyFont = new iTextSharp.text.Font(FontBase, 12); static iTextSharp.text.Font titleFont = new iTextSharp.text.Font(FontBase, 18); static iTextSharp.text.Font paragraphFont = new iTextSharp.text.Font(FontBase, 15); static iTextSharp.text.Font linkFont = new iTextSharp.text.Font(FontBase, 12, Font.UNDERLINE, BaseColor.BLUE);
2.產生PDF檔案流返回byte數組
public byte[] DocCreate(System.Drawing.Image image, List<TreeNodes> list) { MemoryStream file = new MemoryStream(); string fileName = string.Empty; Rectangle page = PageSize.A4; float y = page.Height; Document document = new Document(page, 15, 15, 30, 30); float docWidth = page.Width - 15 * 2; float docHeight = page.Height - document.BottomMargin - document.TopMargin; PdfWriter writer = PdfWriter.GetInstance(document, file); writer.CloseStream = false; writer.Open(); PdfContentByte cb = writer.DirectContent; document.Open(); //標題 Paragraph title = new Paragraph(new Chunk("標題", titleFont)); title.Alignment = Element.ALIGN_CENTER; document.Add(title); //圖片 iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(image, ImageFormat.Png); float widthSzie = (page.Width - 30) / img.Width; if (widthSzie < 1) { img.ScalePercent(widthSzie * 100); } document.Add(img); //文獻出處 Paragraph p2 = new Paragraph(new Chunk("出處", paragraphFont)); p2.IndentationLeft = indentationLeft; document.Add(p2); InitData(list);//初始化業務資料 CreateSteps(list, document, list.FirstOrDefault(it => it.PID == 0));//添加業務資料 ////添加印章 //iTextSharp.text.Image whyz = iTextSharp.text.Image.GetInstance(whyzPath); //whyz.ScalePercent(50); //whyz.PaddingTop = 100; //whyz.Alignment = Element.ALIGN_RIGHT; //document.Add(whyz); //添加日期 Paragraph createtime = new Paragraph(new Chunk(DateTime.Now.ToLongDateString().ToString(), bodyFont)); createtime.Alignment = Element.ALIGN_RIGHT; //createtime.SpacingBefore = -80; createtime.PaddingTop = 200; document.Add(createtime); document.Close(); file.Position = 0; MemoryStream newfile = SetWaterMark(file, "浮水印內容", docWidth, docHeight);//添加浮水印,見另外一篇部落格 newfile.Position = 0;//重設流指標位置 byte[] bytes = new byte[newfile.Length]; newfile.Read(bytes, 0, bytes.Length); return bytes; }