Esempio n. 1
0
        public void AddWeizhu(string filename, string str)
        {
            Dictionary <string, object> dic = new Dictionary <string, object> {
                { "内容", this.Hulue(str.Trim()) }
            };
            var    list = _sqlhelper.GetAnySet(Setting._cijuchachongbiao, dic);
            string text = list[0]["来源"].ToString();

            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(filename);
            TextSelection[] selectionArray = document.FindAllString(str, false, true);
            if (selectionArray != null)
            {
                TextSelection[] selectionArray2 = selectionArray;
                int             index           = 0;
                while (true)
                {
                    if (index >= selectionArray2.Length)
                    {
                        document.SaveToFile(filename);
                        document.Dispose();
                        this.ClearShuiyin(filename);
                        break;
                    }
                    TextSelection             selection = selectionArray2[index];
                    Spire.Doc.Fields.Footnote entity    = selection.GetAsOneRange().OwnerParagraph.AppendFootnote(Spire.Doc.FootnoteType.Endnote);
                    entity.TextBody.AddParagraph().AppendText(text);
                    Paragraph ownerParagraph = selection.GetAsOneRange().OwnerParagraph;
                    ownerParagraph.ChildObjects.Insert(ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange()) + 1, entity);
                    index++;
                }
            }
        }
Esempio n. 2
0
        private void PdfExtractWordAndPicture(string savePathCache, string midName)//参数:保存地址,处理过程中文件名称(不包含后缀)
        {
            #region   提取PDF中的文字

            try
            {
                PdfDocument doc = new PdfDocument();
                doc.LoadFromFile(savePathCache + "\\" + midName + ".pdf");      //加载文件
                StringBuilder content = new StringBuilder();
                foreach (PdfPageBase page in doc.Pages)
                {
                    content.Append(page.ExtractText());
                }


                System.IO.File.WriteAllText(savePathCache + "\\mid.txt", content.ToString());

                Spire.Doc.Document document = new Spire.Doc.Document();
                document.LoadFromFile(savePathCache + "\\mid.txt");
                document.Replace(" ", "", true, true);
                document.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", "", true, true);
                document.SaveToFile(savePathCache + "\\" + midName + ".doc", Spire.Doc.FileFormat.Doc);

                File.Delete(savePathCache + "\\mid.txt");
            }
            catch (Exception)
            {
                MessageBox.Show("请填写正确的路径");
            }
            #endregion

            #region  提取PDF中的图片
            //创建一个PdfDocument类对象并加载PDF sample
            Spire.Pdf.PdfDocument mydoc = new Spire.Pdf.PdfDocument();
            mydoc.LoadFromFile(savePathCache + "\\" + midName + ".pdf");

            //声明一个IList类,元素为image
            IList <Image> images = new List <Image>();
            //遍历PDF文档中诊断是否包含图片,并提取图片
            foreach (PdfPageBase page in mydoc.Pages)
            {
                if (page.ExtractImages() != null)
                {
                    foreach (Image image in page.ExtractImages())
                    {
                        images.Add(image);
                    }
                }
            }
            mydoc.Close();

            //遍历提取的图片,保存并命名图片
            int index = 0;
            foreach (Image image in images)
            {
                String imageFileName = String.Format(midName + "Image-{0}.png", index++);
                image.Save(savePathCache + "\\" + imageFileName, ImageFormat.Png);
            }
            #endregion
        }
Esempio n. 3
0
        /// <summary>
        /// 将word保存为doc格式
        /// </summary>
        /// <param name="o"></param>
        public void SaveDoc(object o)
        {
            string file = o as string;
            //保存文档为doc格式
            string parent  = Directory.GetParent(MySetting.Default.fieldirectory).FullName;
            string savedir = file.Replace(parent, "");

            if (!Directory.Exists(savedir))
            {
                Directory.CreateDirectory(savedir);
            }
            string filename = Path.GetFileNameWithoutExtension(file);
            string savepath = savedir + "\\" + filename + ".docx";

            Spire.Doc.Document mydoc = new Spire.Doc.Document();
            mydoc.SaveToFile(savepath, FileFormat.Docx);

            mydoc.Close();

            //去水印
            Aspose.Words.Document aspdoc = new Aspose.Words.Document(savepath);
            aspdoc.Sections[0].Body.Paragraphs.RemoveAt(0);
            aspdoc.Save(savedir + "\\" + filename + ".doc", Aspose.Words.SaveFormat.Doc);
            //删除docx文件
            File.Delete(savepath);
        }
Esempio n. 4
0
        /// <summary>
        /// 获得一个文档内所有下划线的句子
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public List <string> GetRedLine(string filename)
        {
            List <string> list_result = new List <string>();

            Spire.Doc.Document mydoc = new Spire.Doc.Document(filename);
            //提取所有的标准句
            List <string> list_biaozhunju = GetBiaozhunJuFromFile(filename);

            foreach (string str0 in list_biaozhunju)
            {
                //过滤忽略词
                string str   = Hulue(str0);
                var    texts = mydoc.FindAllString(str, false, true);
                if (texts == null)
                {
                    continue;
                }
                foreach (TextSelection text in texts)
                {
                    var underline = text.GetAsOneRange().CharacterFormat.UnderlineStyle;
                    if (underline == UnderlineStyle.Double)
                    {
                        list_result.Add(str);
                    }
                }
            }
            return(list_result);
        }
        /// <summary>
        /// Получить временный поток сконвертированного документа.
        /// </summary>
        /// <param name="document_bytes">Входящие байты текущего документа</param>
        /// <param name="tempFilePath">Путь сохранения файла</param>
        /// <returns>Временный поток нового файла (В случае ошибки вернёт null)</returns>
        public static MemoryStream getConvertFileDoc(byte[] document_bytes, string tempFilePath)
        {
            using (MemoryStream fileStream = new MemoryStream(document_bytes))
            {
                HLogger.log.Debug("Чтение MemoryStream");

                SPD.Document document = new SPD.Document(fileStream);

                HLogger.log.Debug("Инициализация документа:");

                if (!File.Exists(tempFilePath))
                {
                    document.SaveToFile(tempFilePath, SPD.FileFormat.PDF);
                    HLogger.log.Debug("Сохранение временного файла");
                }
                else
                {
                    HLogger.log.Debug("Подобный временный файл уже существует");
                }

                try
                {
                    MemoryStream result = new MemoryStream(File.ReadAllBytes(tempFilePath));
                    return(result);
                }
                catch
                {
                    HLogger.log.Error("Ошибка при создании временного потока");
                    return(null);
                }
            }
        }
Esempio n. 6
0
        private void BtnDoc_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();
            Person         person     = new Person();
            string         path       = person.FilePath;

            fileDialog.Filter = "Text documents (.doc)|*.doc";
            fileDialog.Title  = "Save an Doc File";

            if (fileDialog.ShowDialog() == true)
            {
                string fileName = fileDialog.FileName;
                string extesion = System.IO.Path.GetExtension(fileName);
                switch (extesion)
                {
                case ".doc":    //do something here
                    Spire.Doc.Document document = new Spire.Doc.Document();
                    document.LoadText(path);
                    document.SaveToFile(fileName, FileFormat.Doc);
                    document.Close();

                    MessageBox.Show("Conversion Successful....");
                    break;
                }
            }

            /*
             * document.SaveToFile(System.IO.Path.Combine(path, "TestWordDoc.docx"), FileFormat.Doc);
             * document.LoadFromFile(System.IO.Path.Combine(path, "TestTxt.txt"));
             *
             * document.LoadFromFile(System.IO.Path.Combine(docPath, "TestWordDoc.docx"));
             * string readText = File.ReadAllText(System.IO.Path.Combine(docPath, "TestTxt.txt"));
             */
        }
Esempio n. 7
0
        /// <summary>
        /// 添加尾注
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="str"></param>
        public void AddWeizhu(string filename, string str)
        {
            //获得数据库中str对应的来源
            string str_sql = $"select 来源 from {Setting._cijuchachongbiao} where 内容='{Hulue(str.Trim())}'";
            Dictionary <string, object> dic = mysqliter.ExecuteRow(str_sql, null, null)[0] as Dictionary <string, object>;
            string laiyuan = dic["来源"].ToString();

            Spire.Doc.Document mydoc = new Spire.Doc.Document();
            mydoc.LoadFromFile(filename);
            TextSelection[] texts = mydoc.FindAllString(str, false, true);
            if (texts == null)
            {
                return;
            }
            //给所有查找到的文字添加脚注
            foreach (TextSelection item in texts)
            {
                //实例化一个脚注的同时,直接创建在指定textselection所在的段落
                Spire.Doc.Fields.Footnote footnote = item.GetAsOneRange().OwnerParagraph.AppendFootnote(Spire.Doc.FootnoteType.Endnote);
                //向脚注内添加文字
                footnote.TextBody.AddParagraph().AppendText(laiyuan);
                //获得这个自然段
                Spire.Doc.Documents.Paragraph mypara = item.GetAsOneRange().OwnerParagraph;
                //向这个段落内的子节点添加脚注
                mypara.ChildObjects.Insert(mypara.ChildObjects.IndexOf(item.GetAsOneRange()) + 1, footnote);
            }
            mydoc.SaveToFile(filename);
            mydoc.Dispose();
            //去水印
            ClearShuiyin(filename);
        }
Esempio n. 8
0
        private void BtnPdf_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();
            Person         person     = new Person();
            string         path       = person.FilePath;
            string         imgPath    = person.ImagePath;

            fileDialog.Filter = "Text documents (.pdf)|*.pdf";
            fileDialog.Title  = "Save an Pdf File";

            if (fileDialog.ShowDialog() == true)
            {
                string fileName = fileDialog.FileName;
                string extesion = System.IO.Path.GetExtension(fileName);
                switch (extesion)
                {
                case ".pdf":
                    Spire.Doc.Document document = new Spire.Doc.Document();
                    document.LoadText(path);
                    document.SaveToFile(fileName, FileFormat.PDF);

                    document.Close();
                    MessageBox.Show("Conversion Successful....");
                    break;
                }
            }
            //  this.Close();
        }
Esempio n. 9
0
        private static string ReplaceImages(Spire.Doc.Document document, string html)
        {
            int index = 1;

            foreach (Section section in document.Sections)
            {
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            DocPicture picture = docObject as DocPicture;
                            using (var memoryStream = new MemoryStream())
                            {
                                picture.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                                string base64Image = System.Convert.ToBase64String(memoryStream.ToArray());
                                html = html.Replace("src=\"_images/_img" + index + ".png\"", imagePrefix + base64Image + "\"").
                                       Replace("src=\"_images/_img" + index + ".jpeg\"", imagePrefix + base64Image + "\"");
                                index++;
                            }
                        }
                    }
                }
            }
            return(html);
        }
Esempio n. 10
0
 /// <summary>
 /// Convert doc or docx to html with picture files
 /// </summary>
 /// <param name="inputFileName">Absolute name of input file</param>
 /// <param name="outputFolder">Folder for saving results</param>
 /// <param name="newFileName">Relative filename of new html</param>
 public static void ConvertToHtml(string inputFileName, string outputFolder, string newFileName, Dictionary <string, string> parameters)
 {
     if (!Directory.Exists(outputFolder))
     {
         Directory.CreateDirectory(outputFolder);
     }
     Spire.Doc.Document document = new Spire.Doc.Document(inputFileName);
     using (var stream = new MemoryStream())
     {
         document.SaveToStream(stream, Spire.Doc.FileFormat.Html);
         string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
         if (result.IndexOf(replaceValueDocx) < 0 && result.IndexOf(replaceValueDoc) < 0)
         {
             result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "").Replace(replaceValue, "");
         }
         else
         {
             result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "");
         }
         AddImages(document, outputFolder, ref result);
         File.WriteAllText(outputFolder + "/" + newFileName, result, Encoding.UTF8);
         result = null;
     }
     document.Dispose();
 }
Esempio n. 11
0
        private void FormEmail_Load(object sender, EventArgs e)
        {
            txtHost.Text     = settings.Host;
            txtForm.Text     = settings.From;
            txtName.Text     = settings.Name;
            txtPassword.Text = settings.Password;
            txtSubjec.Text   = settings.EmailSubject;
            txtPort.Text     = settings.Port;
            if (settings.Encryption == "SSL")

            {
                comboBox1.SelectedIndex = 1;
            }
            else if (settings.Encryption == "")
            {
                comboBox1.SelectedIndex = 0;
            }
            DirectoryInfo d = new DirectoryInfo(textBox2.Text + "\\"); //Assuming Test is your Folder

            FileInfo[] Files = d.GetFiles(".\\" + "email*.dotx");      //Getting Text files
            if (Files.Length == 0)
            {
                //Create word document
                Document document = new Document();

                Paragraph p       = document.AddSection().AddParagraph();
                TextRange txtRang = p.AppendText("H63TWX11072");
                txtRang.CharacterFormat.FontName  = "C39HrP60DlTt";
                txtRang.CharacterFormat.FontSize  = 80;
                txtRang.CharacterFormat.TextColor = Color.SeaGreen;
                Section section = document.AddSection();

                //Initialize a Header Instance
                HeaderFooter header = document.Sections[0].HeadersFooters.Header;
                //Add Header Paragraph and Format
                Paragraph paragraph = header.AddParagraph();
                paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;
                //Append Picture for Header Paragraph and Format
                Spire.Doc.Fields.DocPicture headerimage = paragraph.AppendPicture(Image.FromFile(@"dackeasy_logo.png"));
                headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom;

                paragraph = section.AddParagraph();
                string str = "Dear <CONTACT PERSON>," + "\r\n";
                paragraph.AppendText(str);

                str = "As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers.NET applications.As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers’.NET applications." + "\r\n";
                paragraph.AppendText(str);

                document.SaveToFile("email.dotx", FileFormat.Dotx);
                d = new DirectoryInfo(Directory.GetCurrentDirectory());//Assuming Test is your Folder

                Files = d.GetFiles("email*.dotx");
            }


            comboBox2.DataSource    = Files;
            comboBox2.DisplayMember = "demo";

            //Center(this);
        }
        // Cохранение файла DOC
        private void LoadDoc_Click(object sender, RoutedEventArgs e)
        {
            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(pathDOC);
            document.SaveToFile("ScheduleByCorrespondence.HTML", Spire.Doc.FileFormat.Html);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://212.86.101.101/ScheduleByCorrespondence.html");

            request.Method      = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("anonymous", "");
            byte[] fileContents;
            using (StreamReader sourceStream = new StreamReader(pathDOC))
            {
                fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            }

            request.ContentLength = fileContents.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(fileContents, 0, fileContents.Length);
            }

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                Message.Content = ($"Upload File Complete, status {response.StatusDescription}");
            }
        }
Esempio n. 13
0
        public decimal CalculateImageInFile(string FileFormatInDoc)
        {
            LoadDocument();

            Decimal pixelHeight = 96;
            Decimal pixelWidthl = 96;
            Decimal pixelArea   = pixelHeight * pixelWidthl;
            Decimal amount      = multiplier;
            Decimal finalAmount = 0;

            Spire.Doc.Document document = new Spire.Doc.Document(FileFormatInDoc);
            int index = 0;

            //Create a new Que
            Queue <ICompositeObject> containers = new Queue <ICompositeObject>();

            //Put the document Objects in the queue
            containers.Enqueue(document);

            while (containers.Count > 0)
            {
                ICompositeObject container = (ICompositeObject)containers.Dequeue();

                IDocumentObjectCollection docObjects = container.ChildObjects;

                foreach (DocumentObject docObject in docObjects)
                {
                    //judge the object type

                    if (docObject.DocumentObjectType == Spire.Doc.Documents.DocumentObjectType.Picture)
                    {
                        DocPicture picture = docObject as DocPicture;

                        decimal picHeight = pixelToInches(picture.Height + (picture.Height * 0.33));
                        decimal picWidth  = pixelToInches(picture.Width + (picture.Width * 0.33));
                        decimal picArea   = picHeight * picWidth;

                        finalAmount = finalAmount + (picArea * amount);
                        //'Name the image.
                        //'Dim imageName As String = String.Format("Image-{0}.png", index)
                        //'Save the image.
                        //'picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png)
                        index += 1;
                    }
                    else
                    {
                        if (docObject is ICompositeObject)
                        {
                            containers.Enqueue(docObject as ICompositeObject);
                        }
                    }
                }
            }
            //MessageBox.Show(Convert.ToString(Math.Round(finalAmount, 0)), "Output");
            var value = Convert.ToString(Math.Round(finalAmount, 0));

            return(Convert.ToDecimal(value));
        }
Esempio n. 14
0
        public void FormatSet(Spire.Doc.Document mydoc, List <Microsoft.Office.Interop.Word.Paragraphs> listp, Format f)
        {
            int num = 0;

            while (true)
            {
                while (true)
                {
                    if (num >= listp.Count)
                    {
                        return;
                    }
                    listp[num].Last.Range.Font.Name = f.fontname;
                    listp[num].Last.Range.Font.Size = f.fontsize;
                    string lstype = f.lstype;
                    if (lstype != null)
                    {
                        if (lstype == "单倍行距")
                        {
                            listp[num].Last.Range.Paragraphs.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;
                            break;
                        }
                        if (lstype == "1.5倍行距")
                        {
                            listp[num].Last.Range.Paragraphs.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpace1pt5;
                            break;
                        }
                        if (lstype == "2倍行距")
                        {
                            listp[num].Last.Range.Paragraphs.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceDouble;
                            break;
                        }
                    }
                    listp[num].Last.Range.Paragraphs.LineSpacing = f.lsvalue;
                    break;
                }
                listp[num].Last.Range.Paragraphs.CharacterUnitFirstLineIndent = f.suojin;
                listp[num].Last.Range.Font.Bold = f.bold;
                string juzhong = f.juzhong;
                if (juzhong != null)
                {
                    if (juzhong == "左对齐")
                    {
                        listp[num].Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    }
                    else if (juzhong == "居中")
                    {
                        listp[num].Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
                    else if (juzhong == "右对齐")
                    {
                        listp[num].Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                    }
                }
                num++;
            }
        }
Esempio n. 15
0
        private void button1_Click(object sender, EventArgs e)
        {
            #region   将pdf分成许多份小文档
            Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
            pdf.LoadFromFile(textBox1.Text);
            label4.Text = "转换中......";
            label4.Refresh();
            for (int i = 0; i < pdf.Pages.Count; i += 5)
            {
                int j = 0;
                Spire.Pdf.PdfDocument newpdf = new Spire.Pdf.PdfDocument();
                for (j = i; j >= i && j <= i + 4; j++)
                {
                    if (j < pdf.Pages.Count)
                    {
                        Spire.Pdf.PdfPageBase page;
                        page = newpdf.Pages.Add(pdf.Pages[j].Size, new Spire.Pdf.Graphics.PdfMargins(0));
                        pdf.Pages[j].CreateTemplate().Draw(page, new PointF(0, 0));
                    }
                }
                newpdf.SaveToFile(textBox2.Text + "\\" + j.ToString() + ".pdf");
                PdfExtractWordAndPicture(textBox2.Text, j.ToString());
            }
            #endregion


            #region  合并word文档

            string filePath0 = textBox2.Text + "\\" + '5' + ".doc";
            for (int i = 10; i <= 0 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5)
            {
                string filePath2 = textBox2.Text + "\\" + i.ToString() + ".doc";

                Spire.Doc.Document doc = new Spire.Doc.Document(filePath0);
                doc.InsertTextFromFile(filePath2, Spire.Doc.FileFormat.Doc);

                doc.SaveToFile(filePath0, Spire.Doc.FileFormat.Doc);
            }
            Spire.Doc.Document mydoc1 = new Spire.Doc.Document();
            mydoc1.LoadFromFile(textBox2.Text + "\\" + '5' + ".doc");
            mydoc1.SaveToFile(textBox2.Text + "\\" + "TheLastTransform" + ".doc", Spire.Doc.FileFormat.Doc);

            for (int i = 5; i <= 5 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5)
            {
                File.Delete(textBox2.Text + "\\" + i.ToString() + ".doc");
                File.Delete(textBox2.Text + "\\" + i.ToString() + ".pdf");
            }

            #endregion

            label4.Text = "转换完成";
            label4.Refresh();
        }
Esempio n. 16
0
        /// <summary>
        /// 列印資料
        /// </summary>
        /// <param name="print_title">列印標題</param>
        /// <param name="template_file">樣版檔案</param>
        /// <param name="replace_dic_list">List(Dictionary)資料</param>
        /// <param name="output_type">輸出類型(預設PDF)</param>
        /// <returns>byte[]</returns>
        public byte[] print(string print_title, string template_file, List <Dictionary <string, string> > replace_dic_list, string output_type = "pdf")
        {
            byte[] print_byte = null;
            //新增一個word檔案並加載,樣版檔案
            Spire.Doc.Document document = new Spire.Doc.Document();

            //取得副檔名
            string extension = string.IsNullOrEmpty(Path.GetExtension(template_file)) ? "" : Path.GetExtension(template_file).ToLower();

            List <byte[]> pdf_byte_list = new List <byte[]>();
            int           loop_i        = 0;

            foreach (Dictionary <string, string> dic in replace_dic_list)
            {
                switch (extension)
                {
                case ".docx":
                    document.LoadFromFileInReadMode(template_file, Spire.Doc.FileFormat.Docx2013);
                    break;

                default:
                    break;
                }
                //置換識別字,[$變數名稱$]
                Regex regEx = new Regex(@"\[\$\w*\$\]");
                //尋找識別字
                TextSelection[] selections = document.FindAllPattern(regEx);
                foreach (TextSelection ts in selections)
                {
                    TextRange range        = ts.GetAsOneRange();
                    string    sel_text     = ts.SelectedText.Replace("[$", "").Replace("$]", "");
                    string    replace_text = range.Text;

                    //嘗試置換字符串
                    dic.TryGetValue(sel_text, out replace_text);
                    range.Text = replace_text;
                }
                using (MemoryStream ms = new MemoryStream())
                {
                    document.SaveToStream(ms, Spire.Doc.FileFormat.PDF);
                    //save to byte array
                    pdf_byte_list.Add(ms.ToArray());
                    ms.Close();
                }
                loop_i++;
            }//foreach

            //合併PDF
            print_byte = MergePDFFiles(pdf_byte_list);
            return(print_byte);
        }//print
Esempio n. 17
0
        private void button5_Click(object sender, RibbonControlEventArgs e)
        {
            ////获取当前文档
            Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
            ////获取文档路径
            //string sfileName_path = doc.Path + @"\"+DateTime.Now.ToLongDateString() +"-"+ doc.Name;
            //doc.SaveAs2(sfileName_path);

            //var WordApp = Globals.ThisAddIn.Application;
            //WordApp.ActiveDocument.InlineShapes.AddPicture("");
            //WordApp.ActiveDocument.Paragraphs.Add(0);

            Sp.Document document = new Sp.Document(doc.FullName);
            MessageBox.Show("OK");
        }
Esempio n. 18
0
        private void button3_Click(object sender, EventArgs e)
        {
            Spire.Doc.Document docSpire = new Spire.Doc.Document(@"C:\TEMP\Teste6.docx");
            //Spire.Doc.Document docSpire = new Spire.Doc.Document();
            Spire.Doc.Section             secao     = docSpire.Sections[0];
            Spire.Doc.HeaderFooter        cabecalho = secao.HeadersFooters.Header;
            Spire.Doc.Documents.Paragraph para1     = cabecalho.AddParagraph();
            para1.AppendRTF(richTextBox1.Rtf);

            //Spire.Doc.Section secao2 = docSpire.AddSection();
            Spire.Doc.Documents.Paragraph para2 = secao.AddParagraph();
            para2.AppendRTF(richTextBox2.Rtf);

            docSpire.SaveToFile(@"C:\TEMP\Teste6.docx");
        }
Esempio n. 19
0
        public void CleanFile()
        {
            //Instantiate a Document object
            Spire.Doc.Document document = new Spire.Doc.Document();
            //Load the Word document
            document.LoadFromFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx");

            //Remove paragraphs from every section in the document
            foreach (Spire.Doc.Section section in document.Sections)
            {
                section.Paragraphs.Clear();
            }

            //Save the document
            document.SaveToFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx", FileFormat.Docx2013);
        }
Esempio n. 20
0
        static Stream BRtfDocx(byte[] byteArray)
        {
            MemoryStream ms       = new MemoryStream(byteArray);
            MemoryStream msout    = new MemoryStream();
            StreamReader sReader  = new StreamReader(ms);
            var          document = new Spire.Doc.Document();

            //document.LoadFromFile(@"test-doc.rtf");
            ms.Seek(0, SeekOrigin.Begin);
            document.LoadRtf(ms, Encoding.UTF8);
            document.SaveToStream(msout, FileFormat.Docx);
            msout.Seek(0, SeekOrigin.Begin);
            //StreamReader reader = new StreamReader(msout);
            //string text = reader.ReadToEnd();
            return(msout);
        }
Esempio n. 21
0
        private void button5_Click(object sender, EventArgs e)
        {
            Spire.Doc.Document doc1 = new Spire.Doc.Document();

            doc1.LoadFromFile(@"C:\Downloads\Tax_Header_Document.docx");
            Spire.Doc.HeaderFooter header = doc1.Sections[0].HeadersFooters.Header;
            Spire.Doc.Document     doc2   = new Spire.Doc.Document(@"C:\Downloads\2301-233608- Tax Cert.docx");
            foreach (Spire.Doc.Section section in doc2.Sections)
            {
                foreach (DocumentObject obj in header.ChildObjects)
                {
                    section.HeadersFooters.Header.ChildObjects.Add(obj.Clone());
                }
            }
            //doc2.SaveToFile(@"C:\Downloads\TAx_Final.docx", Spire.Doc.FileFormat.Docx);
        }
Esempio n. 22
0
        public static string Parse(FileStream file)
        {
            string retVal = "";

            try
            {
                Spire.Doc.Document doc = new Spire.Doc.Document(file);
                retVal = doc.GetText();
            }
            catch (Exception ex)
            {
                ParsersInfra.RecordParsingFailure(Log, ex, file);
            }

            return(retVal);
        }
Esempio n. 23
0
        //Copies mail merge template into .docx and adds page break
        public void AddTemplate()
        {
            Spire.Doc.Document sourceDoc      = new Spire.Doc.Document(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QR.docx");
            Spire.Doc.Document destinationDoc = new Spire.Doc.Document(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx");
            foreach (Spire.Doc.Section sec in sourceDoc.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());

                    Spire.Doc.Documents.Paragraph newParagraph = new Spire.Doc.Documents.Paragraph(destinationDoc);
                    newParagraph.AppendBreak(BreakType.PageBreak);
                    destinationDoc.LastSection.Paragraphs.Add(newParagraph);
                }
            }
            destinationDoc.SaveToFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx", FileFormat.Docx2013);
        }
Esempio n. 24
0
 static void Main(string[] args)
 {
     using (var stream = new MemoryStream())
     {
         // Generate RTF (using MigraDoc)
         var migraDoc  = new MigraDoc.DocumentObjectModel.Document();
         var section   = migraDoc.AddSection();
         var paragraph = section.AddParagraph();
         paragraph.AddFormattedText("Hello World!", TextFormat.Bold);
         var rtfDocumentRenderer = new RtfDocumentRenderer();
         rtfDocumentRenderer.Render(migraDoc, stream, false, null);
         // Convert RTF to DOCX (using Spire.Doc)
         var spireDoc = new Spire.Doc.Document();
         spireDoc.LoadFromStream(stream, FileFormat.Auto);
         spireDoc.SaveToFile("D:\\example.docx", FileFormat.Docx);
     }
 }
Esempio n. 25
0
        private static StringBuilder WordToText(string fullName)
        {
            Spire.Doc.Document doc = new Spire.Doc.Document();
            doc.LoadFromFile(fullName);

            // Initilize StringBuilder Instance
            StringBuilder toText = new StringBuilder();

            //Extract Text from Word and Save to StringBuilder Instance
            foreach (Section section in doc.Sections)
            {
                foreach (SDocuments.Paragraph paragraph in section.Paragraphs)
                {
                    toText.AppendLine(paragraph.Text);
                }
            }
            return(toText);
        }
Esempio n. 26
0
        static void Ziple()
        {
            string inputPath = "C:/Users/Administrator/Desktop/metinDeneme.docx";


            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(inputPath);

            //Convert Word to PDF
            document.SaveToFile("metin.PDF", FileFormat.PDF);
            byte[] array = File.ReadAllBytes("metin.PDF");

            webReferans.WebService1 ws = new webReferans.WebService1();
            byte[] zipByteArray        = ws.ZipThat("metin.pdf", array);
            File.WriteAllBytes("C:/Users/Administrator/Desktop/test.zip", zipByteArray);

            Console.WriteLine("İşlem Başarılı .");
            Console.ReadLine();
        }
        private void Finalizer(Content content)
        {
            using (var outputDocument = new TemplateProcessor(_outputPath)
                                        .SetRemoveContentControls(true))
            {
                outputDocument.FillContent(content);
                outputDocument.SaveChanges();
            }


            Document document = new Document();

            document.LoadFromFile(_outputPath);

            //Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF);


            //Launch Document
            Process.Start("toPDF.PDF");
        }
Esempio n. 28
0
        /// <summary>
        /// Convert doc or docx to html with base64 pictures
        /// </summary>
        /// <param name="inputFileName">Absolute name of input file</param>
        /// <param name="outputFileName">Absolute name of output file</param>
        public static void ConvertToHtml(string inputFileName, string outputFileName)
        {
            Spire.Doc.Document document = new Spire.Doc.Document(inputFileName);
            using (var stream = new MemoryStream())
            {
                string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                document.SaveToStream(stream, Spire.Doc.FileFormat.Html);
                if (result.IndexOf(replaceValueDocx) < 0 && result.IndexOf(replaceValueDoc) < 0)
                {
                    result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "").Replace(replaceValue, "");
                }
                else
                {
                    result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "");
                }
                result = ReplaceImages(document, result);

                File.WriteAllText(outputFileName, result, Encoding.UTF8);
                result = null;
            }
            document.Dispose();
        }
Esempio n. 29
0
        public List <string> GetRedLine(string filename)
        {
            List <string> list = new List <string>();

            Spire.Doc.Document document = new Spire.Doc.Document(filename);
            foreach (string str in this.GetBiaozhunJuFromFile(filename))
            {
                string          matchString    = this.Hulue(str);
                TextSelection[] selectionArray = document.FindAllString(matchString, false, true);
                if (selectionArray != null)
                {
                    foreach (TextSelection selection in selectionArray)
                    {
                        if (selection.GetAsOneRange().CharacterFormat.UnderlineStyle == UnderlineStyle.Double)
                        {
                            list.Add(matchString);
                        }
                    }
                }
            }
            return(list);
        }
Esempio n. 30
0
        static void MultiZiple()
        {
            string inputPath1 = "C:/Users/Administrator/Desktop/metinDeneme.docx";
            string inputPath2 = "C:/Users/Administrator/Desktop/metinDeneme2.docx";

            Spire.Doc.Document doc1 = new Spire.Doc.Document();
            Spire.Doc.Document doc2 = new Spire.Doc.Document();

            doc1.LoadFromFile(inputPath1);
            doc2.LoadFromFile(inputPath2);

            doc1.SaveToFile("metin1.PDF", FileFormat.PDF);
            doc2.SaveToFile("metin2.PDF", FileFormat.PDF);

            byte[] metin1_Array = File.ReadAllBytes("metin1.PDF");
            byte[] metin2_Array = File.ReadAllBytes("metin2.PDF");

            webReferans.WebService1 ws = new webReferans.WebService1();

            byte[] multiZipArray = ws.ZipMulti("metin1.PDF", "metin2.PDF", metin1_Array, metin2_Array);

            File.WriteAllBytes("C:/Users/Administrator/Desktop/testMultiZip.zip", multiZipArray);
        }