欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#生成PDF文件流

程序员文章站 2022-10-12 23:42:13
本文实例为大家分享了c#生成pdf文件流的具体代码,供大家参考,具体内容如下 1、设置字体 static basefont fontbase = basefon...

本文实例为大家分享了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;
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。