C# PDF转图片,Word转图片并生成新的Word和PDF方法

1、生成Word和PDF方法,其原理就是抓取word和pdf中的所有内容并转换为图片,然后生成新的word和pdf

 public void FileToPDF(byte[] fileBytes, Section section, MES_MonitoringDeviceModel mdl, string filePath, string type, bool isPage)
 {
     using (MemoryStream ms = new MemoryStream(fileBytes))
     {
         // Section section1 = doc.Sections[0];// doc.AddSection();
         Paragraph para = section.AddParagraph();
         //para.Format.LeftIndent = -25; // 设置左缩进为 0
         para.AppendText((mdl.PROPERTY_NO + "-" + mdl.EQUIPMENTDESC + "-" + mdl.EQUIPMENTMODEL + "-" + type).TrimStart());
         para.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
         para.Format.LineSpacingRule = LineSpacingRule.Multiple;
         para.Format.LineSpacing = 1.5f;
         para.Format.PageBreakBefore = true; // 段前分页
         Paragraph parak = section.AddParagraph();

         if (Path.GetExtension(filePath).ToLower() == ".pdf")
         {
             // 如果是 PDF 文件
             using (Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument())
             {
                 pdf.LoadFromStream(ms);

                 for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)
                 {
                     // 将每一页转换为图片
                     System.Drawing.Image image = pdf.SaveAsImage(pageIndex);

                     // 调整图片尺寸
                     int originalWidth = image.Width;
                     int originalHeight = image.Height;
                     int maxWidth = 550; // 设置最大宽度
                     int maxHeight = 1000; // 设置最大高度

                     float ratio = Math.Min((float)maxWidth / originalWidth, (float)maxHeight / originalHeight);
                     int newWidth = (int)(originalWidth * ratio);
                     int newHeight = (int)(originalHeight * ratio);

                     var resizedImage = new Bitmap(image, newWidth, newHeight);

                     // 将图片插入到 Word 文档中
                     Paragraph paraimg = section.AddParagraph();

                     DocPicture picture = paraimg.AppendPicture(resizedImage); // 插入图片
                                                                               // 设置图片居中
                     picture.TextWrappingStyle = TextWrappingStyle.Through;
                     picture.VerticalAlignment = ShapeVerticalAlignment.Center; // 图片顶部对齐
                     picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; // 图片水平居中
                                                                                    // paraimg.Format.PageBreakBefore = false; // 段前分页
                     if ((pageIndex + 1) < pdf.Pages.Count)
                     {
                         paraimg.AppendBreak(BreakType.PageBreak); // 插入分页符
                     }
                 }
             }
         }
         else if (Path.GetExtension(filePath).ToLower().Contains(".doc"))
         {
             Document doc1 = new Document();
             //载入Word文档
             doc1.LoadFromStream(ms, FileFormat.Docx);
             //将整个Word文档转换为位图集合
             System.Drawing.Image[] images = doc1.SaveToImages(ImageType.Metafile);
             for (int i = 0; i < images.Length; i++)
             {
                 // 调整图片尺寸
                 int originalWidth = images[i].Width;
                 int originalHeight = images[i].Height;
                 int maxWidth = 550; // 设置最大宽度
                 int maxHeight = 1000; // 设置最大高度

                 float ratio = Math.Min((float)maxWidth / originalWidth, (float)maxHeight / originalHeight);
                 int newWidth = (int)(originalWidth * ratio);
                 int newHeight = (int)(originalHeight * ratio);

                 var resizedImage = new Bitmap(images[i], newWidth, newHeight);

                 // 将图片插入到 Word 文档中
                 Paragraph paraimg = section.AddParagraph();

                 DocPicture picture = paraimg.AppendPicture(resizedImage); // 插入图片
                                                                           // 设置图片居中
                 picture.TextWrappingStyle = TextWrappingStyle.Through;
                 picture.VerticalAlignment = ShapeVerticalAlignment.Center; // 图片顶部对齐
                 picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; // 图片水平居中
                                                                                // paraimg.Format.PageBreakBefore = false; // 段前分页
                 if ((i + 1) < images.Length)
                 {
                     paraimg.AppendBreak(BreakType.PageBreak); // 插入分页符
                 }
             }
         }
         else
         {

             // 获取图片的原始宽高
             var image = System.Drawing.Image.FromStream(ms);
             int originalWidth = image.Width;
             int originalHeight = image.Height;

             // 设置最大宽度和高度
             int maxWidth = 550; // 设置最大宽度
             int maxHeight = 1000; // 设置最大高度

             // 根据比例调整图片的宽度和高度
             float ratio = Math.Min((float)maxWidth / originalWidth, (float)maxHeight / originalHeight);
             int newWidth = (int)(originalWidth * ratio);
             int newHeight = (int)(originalHeight * ratio);

             // 使用 Graphics 对象调整图片大小
             var newImage = new Bitmap(image, newWidth, newHeight);
             Paragraph paraimg = section.AddParagraph();
             DocPicture picture = paraimg.AppendPicture(newImage); // 插入图片
                                                                   // 设置图片居中
             picture.TextWrappingStyle = TextWrappingStyle.Through;
             picture.VerticalAlignment = ShapeVerticalAlignment.Center; // 图片顶部对齐
             picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; // 图片水平居中
         }
     }
 }
 public void FileToWord(byte[] fileBytes, Document doc, string primaryTitle, string type, bool lenghtT, Paragraph paragraph,
    Spire.Doc.Formatting.CharacterFormat format30, Spire.Doc.Formatting.CharacterFormat format, string filePath, int idx, List<string> types, bool isPage)
 {
     using (MemoryStream ms = new MemoryStream(fileBytes))
     {
         Section section = doc.Sections[0];
         if (isPage)
         {
             //创建段落
             Paragraph para = section.AddParagraph();
             para.Format.ClearFormatting();
             para.ApplyStyle(BuiltinStyle.Heading2); //应用标题1样式  设置之后左侧会出现导航       
             para.ListFormat.ApplyStyle("NoTabStyle"); //应用列表样式 会出现标题序号
             para.ListFormat.ListLevelNumber = 1; //设置等级为第二等级 
                                                  //para.Format.LeftIndent = 0.85f;//
                                                  //para.Format.FirstLineIndent = 0;
                                                  //para.Format.Tabs.Clear(); // 清除所有制表位
                                                  //para.Format.AutoSpaceDE = false;
                                                  //para.Format.AutoSpaceDN = false;

             TextRange trc = para.AppendText((primaryTitle + "-" + type).TrimStart());

             var lenghtTC = primaryTitle.Length > 30;
             if (lenghtT)
             {
                 float fontSize = 10.5f;
                 paragraph.Format.LineSpacingRule = LineSpacingRule.Multiple;
                 paragraph.Format.LineSpacing = fontSize + 2f;
                 trc.ApplyCharacterFormat(format30); //应用字体格式
             }
             else
             {
                 float fontSize = 12f;
                 paragraph.Format.LineSpacingRule = LineSpacingRule.Multiple;
                 paragraph.Format.LineSpacing = fontSize * 1.5f;
                 trc.ApplyCharacterFormat(format); //应用字体格式
             }
         }
         //para.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;
         if (Path.GetExtension(filePath).ToLower() == ".pdf")
         {
             // 如果是 PDF 文件
             using (Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument())
             {
                 pdf.LoadFromStream(ms);
                 for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)
                 {
                     // 将每一页转换为图片
                     System.Drawing.Image image = pdf.SaveAsImage(pageIndex);

                     // 调整图片尺寸
                     int originalWidth = image.Width;
                     int originalHeight = image.Height;
                     int maxWidth = 550; // 设置最大宽度
                     int maxHeight = 1000; // 设置最大高度

                     float ratio = Math.Min((float)maxWidth / originalWidth, (float)maxHeight / originalHeight);
                     int newWidth = (int)(originalWidth * ratio);
                     int newHeight = (int)(originalHeight * ratio);

                     var resizedImage = new Bitmap(image, newWidth, newHeight);

                     Paragraph paraimg = section.AddParagraph();
                     DocPicture picture = paraimg.AppendPicture(resizedImage);
                     // 设置图片居中
                     picture.TextWrappingStyle = TextWrappingStyle.Through;
                     picture.VerticalAlignment = ShapeVerticalAlignment.Center; // 图片顶部对齐
                     picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; // 图片水平居中

                 }
             }
         }
         else if (Path.GetExtension(filePath).ToLower().Contains(".doc"))
         {
             Document doc1 = new Document();
             //载入Word文档
             doc1.LoadFromStream(ms, FileFormat.Docx);
             //将整个Word文档转换为位图集合
             System.Drawing.Image[] images = doc1.SaveToImages(ImageType.Metafile);
             for (int i = 0; i < images.Length; i++)
             {
                 // 调整图片尺寸
                 int originalWidth = images[i].Width;
                 int originalHeight = images[i].Height;
                 int maxWidth = 415; // 设置最大宽度
                 int maxHeight = 690; // 设置最大高度

                 float ratio = Math.Min((float)maxWidth / originalWidth, (float)maxHeight / originalHeight);
                 int newWidth = (int)(originalWidth * ratio);
                 int newHeight = (int)(originalHeight * ratio);

                 var resizedImage = new Bitmap(images[i], newWidth, newHeight);
                 using (Graphics g = Graphics.FromImage(resizedImage))
                 {
                     g.DrawImage(images[i], Point.Empty);
                 }
                 Paragraph paraimg = section.AddParagraph();
                 DocPicture picture = paraimg.AppendPicture(resizedImage);

                 picture.HorizontalAlignment = ShapeHorizontalAlignment.Center;



                 //设置图片大小
                 picture.Width = (float)Convert.ToSingle(newWidth);
                 picture.Height = (float)Convert.ToSingle(newHeight);
                 // 设置图片居中
                 picture.TextWrappingStyle = TextWrappingStyle.Through;
                 picture.VerticalAlignment = ShapeVerticalAlignment.Center; // 图片顶部对齐
                 picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; // 图片水平居中

             }
         }
         else
         {
             // 获取图片的原始宽高
             var image = System.Drawing.Image.FromStream(ms);
             int originalWidth = image.Width;
             int originalHeight = image.Height;

             // 设置最大宽度和高度
             int maxWidth = 550; // 设置最大宽度
             int maxHeight = 1000; // 设置最大高度

             // 根据比例调整图片的宽度和高度
             float ratio = Math.Min((float)maxWidth / originalWidth, (float)maxHeight / originalHeight);
             int newWidth = (int)(originalWidth * ratio);
             int newHeight = (int)(originalHeight * ratio);

             // 使用 Graphics 对象调整图片大小
             var newImage = new Bitmap(image, newWidth, newHeight);
             Paragraph paraimg = section.AddParagraph();
             DocPicture picture = paraimg.AppendPicture(newImage);

             // 设置图片居中
             picture.TextWrappingStyle = TextWrappingStyle.Through;
             picture.VerticalAlignment = ShapeVerticalAlignment.Center; // 图片顶部对齐
             picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; // 图片水平居中
         }
     }
     if (idx + 1 < types.Count)
     {
         Section section = doc.Sections[0];
         Paragraph para = section.AddParagraph();
         // 插入分页符
         //para = section.AddParagraph(); // 新增一个段落
         //para.AppendBreak(BreakType.PageBreak); // 插入分页符
     }
 }

2、生成PDF方法调用,除了doc和section,其余字段均为数据库实体的一些字段,这里不做说明

 Document doc = new Document();
 Section section = doc.AddSection();
//此处可做循环
var s = fba.FileSingleDownload(item.ASDocId); ////流转换字节方法1 byte[] fileByte; using (MemoryStream mst = new MemoryStream()) { s.CopyTo(mst); fileByte = mst.ToArray(); } FileToPDF(fileByte, section, mdl, item.FileName, type, oldType == type ? false : true); //FileToWord(fileByte, doc, primaryTitle, type, lenghtT, paragraph, format30, format, item.FileName, idx, types, oldType == type ? false : true); oldType = type;
//循环结束
   using (MemoryStream ms = new MemoryStream())
   {
       doc.SaveToStream(ms, Spire.Doc.FileFormat.PDF); // 保存为 PDF 格式
       ms.Seek(0, SeekOrigin.Begin);  // 重置流的位置

       byte[] fileBytes = ms.ToArray();

       string filename = mdl.PROPERTY_NO + "-" + mdl.EQUIPMENTDESC + "-" + mdl.EQUIPMENTMODEL + ".pdf";// "Output_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";  // 文件名

       //var filePath1 = "D:\\UploadFiles\\" + filename;
       ////保存为Excel文件  
       //using (FileStream fs = new FileStream(filePath1, FileMode.Create, FileAccess.Write))
       //{
       //    // byte[] infbytes = new byte[(int)fs.Length];
       //    fs.Write(fileBytes, 0, fileBytes.Length);
       //    fs.Flush();
       //}
       // 调用文件上传接口
       string docids = fba.FileSingleUploads(fileBytes, docid, filename);
       if (string.IsNullOrEmpty(docids))
       {
           return new { status = "fail", msg = "文件上传失败" };
       }
       files.Add(docids);
   }

 

3、生成Word方法调用,有些字段是实体字段,此处不做说明

 Document doc = new Document();
 doc.LoadFromFile(templatePath); // 载入模板
 // 4. 替换模板中的占位符 "~~~当前日期~~~" 为当前日期格式化字符串
 string currentDate = DateTime.Now.ToString("yyyy年MM月dd日");
 doc.Replace("{{{当前日期}}}", currentDate, false, true); // 只替换一次,不区分大小写
 #region 初始化ListStyle对象
 //初始化ListStyle对象,指定List类型为数字列表并命名
 ListStyle listStyle = new ListStyle(doc, ListType.Numbered);
 listStyle.Name = "NoTabStyle";
 //设定一级列表模式为阿拉伯数字
 listStyle.Levels[0].NumberPrefix = "";
 listStyle.Levels[0].PatternType = ListPatternType.Arabic; //序号样式儿 阿拉伯数字 1 2
                                                           //listStyle.Levels[0].ParagraphFormat.LeftIndent = 0;  //左端缩进
                                                           //listStyle.Levels[0].TextPosition = 0;//设置列表样式时,强制取消悬挂缩
                                                           //listStyle.Levels[0].ParagraphFormat.FirstLineIndent = 0; //首行左侧缩进
                                                           // listStyle.Levels[0].ParagraphFormat.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; //左对齐

 //设置二级列表数字前缀及模式
 listStyle.Levels[1].NumberPrefix = "%1.";//\x0000.
 listStyle.Levels[1].PatternType = ListPatternType.Arabic;//序号样式儿 阿拉伯数字 1.1 1.2
 listStyle.Levels[1].CharacterFormat.FontName = "宋体";
 listStyle.Levels[1].CharacterFormat.Italic = false;  //非斜体
                                                      //listStyle.Levels[1].TextPosition = 0;//设置列表样式时,强制取消悬挂缩
                                                      //listStyle.Levels[1].ParagraphFormat.FirstLineIndent = 0.85f;//首行左侧缩进
                                                      // listStyle.Levels[1].ParagraphFormat.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; //左对齐


 ////设置三级列表数字前缀及模式
 //listStyle.Levels[2].NumberPrefix = "%1.";//\x0000.\x0001.
 //listStyle.Levels[2].PatternType = ListPatternType.Arabic;
 //listStyle.Levels[2].CharacterFormat.FontName = "宋体";
 //listStyle.Levels[2].CharacterFormat.Italic = false;
 //listStyle.Levels[2].ParagraphFormat.LeftIndent = 0;
 //listStyle.Levels[2].ParagraphFormat.FirstLineIndent = 0;
 //listStyle.Levels[2].ParagraphFormat.HorizontalAlignment =Spire.Doc.Documents.HorizontalAlignment.Left;

 //在ListStyles集合中添加新建的list style
 doc.ListStyles.Add(listStyle);
 #endregion
 //创建字体格式
 Spire.Doc.Formatting.CharacterFormat format = new Spire.Doc.Formatting.CharacterFormat(doc);
 format.FontName = "宋体";
 format.FontSize = 12;
 format.Italic = false;
 Spire.Doc.Formatting.CharacterFormat format30 = new Spire.Doc.Formatting.CharacterFormat(doc);
 format30.FontName = "宋体";
 format30.FontSize = 10.5f;
 format30.Italic = false;  // 确保字体不是斜体
int idx = 0;

// 拼接设备名称和设备型号作为一级标题
string primaryTitle = (mdl.PROPERTY_NO + "-" + mdl.EQUIPMENTDESC + "-" + mdl.EQUIPMENTMODEL).TrimStart(); // 拼接设备名称和设备型号

// 插入一级标题
Section sections = doc.Sections[0]; // 获取文档的第一部分
Paragraph paragraph = sections.AddParagraph();     //创建段落
                                                   //  paragraph.Format.ClearFormatting();
paragraph.ApplyStyle(BuiltinStyle.Heading1); //应用标题1样式  设置之后左侧会出现导航 //paragraph.Format.Tabs.
paragraph.Format.AfterSpacing = 0;////段后间距
paragraph.Format.BeforeSpacing = 0;//段前间距
paragraph.ListFormat.ApplyStyle("NoTabStyle"); //应用列表样式 会出现标题序号
                                               // 直接设置段落分页属性
paragraph.Format.PageBreakBefore = true; // 段前分页
// 确保不被其他设置覆盖
paragraph.Format.KeepFollow = true;
//paragraph.Format.LeftIndent = 0;
//paragraph.Format.FirstLineIndent = 0;
//paragraph.Format.Tabs.Clear(); // 清除所有制表位

TextRange tr = paragraph.AppendText(primaryTitle);
var lenghtT = primaryTitle.Length > 30;
if (lenghtT)
{
    float fontSize = 10.5f;
    paragraph.Format.LineSpacingRule = LineSpacingRule.Multiple;
    paragraph.Format.LineSpacing = fontSize + 2f;
    tr.ApplyCharacterFormat(format30); //应用字体格式
}
else
{
    float fontSize = 12f;
    paragraph.Format.LineSpacingRule = LineSpacingRule.Multiple;
    paragraph.Format.LineSpacing = fontSize * 1.5f;
    tr.ApplyCharacterFormat(format); //应用字体格式
}
string oldType = "";

//此处可做循环处理
  var s = fba.FileSingleDownload(item.ASDocId);
  ////流转换字节方法1
  byte[] fileByte;
  using (MemoryStream mst = new MemoryStream())
  {
      s.CopyTo(mst);
      fileByte = mst.ToArray();
  }
  string name = string.IsNullOrEmpty(Path.GetExtension(item.FileName)) ? item.FileName + "." + item.FileType : item.FileName;
  FileToWord(fileByte, doc, primaryTitle, type, lenghtT, paragraph, format30, format, name, idx, types, oldType == type ? false : true);
  oldType = type;

//循环结束

  Section sectionfenduan = doc.Sections[0];
  Paragraph parafenduan = sectionfenduan.AddParagraph();

 

  

posted @ 2025-05-16 16:10  桎梏110  阅读(71)  评论(0)    收藏  举报