public Document CreatePdf(string strImage) { try { byte[] bytes = Convert.FromBase64String(strImage); Document pdfDocument = new Document(); Page page = pdfDocument.Pages.Add(); using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { Aspose.Pdf.Image pdfImage = new Aspose.Pdf.Image { ImageStream = ms }; page.Paragraphs.Add(pdfImage); MemoryStream ms2 = new MemoryStream(); pdfDocument.Save(ms2); ms2 = null; } return(pdfDocument); } catch (Exception ex) { throw ex; } finally { } }
public static void AddImageAndTable() { // ExStart:AddImageAndTable // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); Document doc = new Document(); Page page = doc.Pages.Add(); TextFragment text = new TextFragment("some text"); page.Paragraphs.Add(text); text.FootNote = new Note(); Aspose.Pdf.Image image = new Aspose.Pdf.Image(); image.File = dataDir + "aspose-logo.jpg"; image.FixHeight = 20; text.FootNote.Paragraphs.Add(image); TextFragment footNote = new TextFragment("footnote text"); footNote.TextState.FontSize = 20; footNote.IsInLineParagraph = true; text.FootNote.Paragraphs.Add(footNote); Aspose.Pdf.Table table = new Aspose.Pdf.Table(); table.Rows.Add().Cells.Add().Paragraphs.Add(new TextFragment("Row 1 Cell 1")); text.FootNote.Paragraphs.Add(table); dataDir = dataDir + "AddImageAndTable_out.pdf"; // Save resulting PDF document. doc.Save(dataDir); // ExEnd:AddImageAndTable Console.WriteLine("\nTable and image added successfully to FootNote.\nFile saved at " + dataDir); }
public PDocument(string fileFullName, HDocument hDocument) { /* * //DEBUG * PDocument_debug(fileFullName, hDocument); * return; */ bodyNode = hDocument.BodyNode; pageTextState = PUtil.TextStateUtil.TextState_Default(); PUtil.TextStateUtil.TextState_ModifyFromHStyles((bodyNode as HNodeTag).Styles, pageTextState); pageMargin = new MarginInfo(4, 4, 4, 12); pageBackground = Aspose.Pdf.Color.FromRgb(1.00, 1.00, 1.00); pdfDocument = new Document(); pdfPage = null; pdfTextFragment = null; pdfImage = null; hyperlinkNode = null; pdfNewLine = null; inlineParagraphMargin = null; pdfFormField = null; pdfRadioButtonFields = new Dictionary <string, RadioButtonField>(); updateCurrentPage(); createBody(); pdfDocument.Save(fileFullName); }
private void GenerateTicket() { var pdf = new Aspose.Pdf.Document(); //Add a page to the document var pdfTicketPage = pdf.Pages.Add(); var strBody = Session["TicketBody"].ToString(); var fragment = new Aspose.Pdf.Text.TextFragment(strBody.ToString()); pdfTicketPage.Paragraphs.Add(fragment); DirectoryInfo dir = new DirectoryInfo(@"D:\Images\"); FileInfo fileInfo = dir.GetFiles("*.jpg").FirstOrDefault(); FileStream stream = new FileStream(fileInfo.FullName, FileMode.Open); System.Drawing.Image img = new System.Drawing.Bitmap(stream); var image = new Aspose.Pdf.Image { ImageStream = stream }; image.FixHeight = 125; image.FixWidth = 300; image.Margin = new MarginInfo(5, 5, 5, 5); pdfTicketPage.Paragraphs.Add(image); pdf.Save(@"D:\Images\Ticket.pdf"); sendEmail(); }
private Aspose.Pdf.Image getImage(HNodeTag imageNode) { /* * int height = 0; * int width = 0; * * using (WebClient webClient = new WebClient()) * { * //var watch = System.Diagnostics.Stopwatch.StartNew(); * * byte[] data = webClient.DownloadData(imageUrl); * * using (MemoryStream imageStream = new MemoryStream(data)) * { * // Add image to Images collection of Page Resources * pdfPage.Resources.Images.Add(imageStream); * * height = pdfPage.Resources.Images[pdfPage.Resources.Images.Count].Height; * width = pdfPage.Resources.Images[pdfPage.Resources.Images.Count].Width; * } * } * //return pdfPage.Resources.Images[pdfPage.Resources.Images.Count]; */ //pdfImage = getImage(((node as HNodeTag).GetAttribute("src", ""))); Aspose.Pdf.Image image = null; string imageUrl = imageNode.GetAttribute("src", ""); try { using (WebClient webClient = new WebClient()) { byte[] imageData = webClient.DownloadData(imageUrl); using (MemoryStream imageStream = new MemoryStream(imageData)) { System.Drawing.Image img = System.Drawing.Image.FromStream(imageStream); image = new Aspose.Pdf.Image(); image.File = imageUrl; image.FixHeight = img.Height; image.FixWidth = img.Width; } } } catch { } return(image); }
private void CovertToPdf(string Destpath, string Sourcepath, Dictionary <GSS.FBU.CMAspose.DomainObject.DomainEnum.CMCustomStyleEnum, string> styles) { string fileName = FileFrom.Text.Trim().Split('\\').Last().Split('.')[1]; string extension = string.Empty; extension = fileName.Split('.').Last().ToLower(); switch (extension) { case "xls": case "xlsx": FileStream fsExcel = new FileStream(Sourcepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); ExcelProcessing pdfStream = new ExcelProcessing(fsExcel); //底層設定客製化樣式 pdfStream.SetCustomStyleProperty(styles); pdfStream.Convert2Pdf(Destpath); /* Workbook excelDocument = new Workbook(Sourcepath); * excelDocument.Save(Destpath , Aspose.Cells.SaveFormat.Pdf);*/ break; case "doc": case "docx": Aspose.Words.Document lDocDocument = new Aspose.Words.Document(Sourcepath); lDocDocument.Save(Destpath, Aspose.Words.SaveFormat.Pdf); break; case "tiff": case "tif": case "png": case "gif": case "jpeg": case "jpg": case "xpm": // Initialize new PDF document Aspose.Pdf.Document doc = new Aspose.Pdf.Document(); // Add empty page in empty document Page page = doc.Pages.Add(); Aspose.Pdf.Image image = new Aspose.Pdf.Image(); image.File = (Sourcepath); // Add image on a page page.Paragraphs.Add(image); // Save output PDF file doc.Save(Destpath); break; default: break; } }
public static void Run() { // ExStart:AddSVGObject // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Tables(); // Instantiate Document object Document doc = new Document(); // Create an image instance Aspose.Pdf.Image img = new Aspose.Pdf.Image(); // Set image type as SVG img.FileType = Aspose.Pdf.ImageFileType.Svg; // Path for source file img.File = dataDir + "SVGToPDF.svg"; // Set width for image instance img.FixWidth = 50; // Set height for image instance img.FixHeight = 50; // Create table instance Aspose.Pdf.Table table = new Aspose.Pdf.Table(); // Set width for table cells table.ColumnWidths = "100 100"; // Create row object and add it to table instance Aspose.Pdf.Row row = table.Rows.Add(); // Create cell object and add it to row instance Aspose.Pdf.Cell cell = row.Cells.Add(); // Add textfragment to paragraphs collection of cell object cell.Paragraphs.Add(new TextFragment("First cell")); // Add another cell to row object cell = row.Cells.Add(); // Add SVG image to paragraphs collection of recently added cell instance cell.Paragraphs.Add(img); // Create page object and add it to pages collection of document instance Page page = doc.Pages.Add(); // Add table to paragraphs collection of page object page.Paragraphs.Add(table); dataDir = dataDir + "AddSVGObject_out_.pdf"; // Save PDF file doc.Save(dataDir); // ExEnd:AddSVGObject Console.WriteLine("\nSVG image added successfully inside a table cell.\nFile saved at " + dataDir); }
public static void AddDicomImage() { //ExStart: AddDicomImage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); using (Document pdfDocument = new Document()) { pdfDocument.Pages.Add(); Aspose.Pdf.Image image = new Aspose.Pdf.Image(); image.FileType = ImageFileType.Dicom; image.ImageStream = new FileStream(dataDir + "0002.dcm", FileMode.Open, FileAccess.Read); pdfDocument.Pages[1].Paragraphs.Add(image); // Save output as PDF format pdfDocument.Save(dataDir + "PdfWithDicomImage_out.pdf"); } //ExEnd: AddDicomImage }
public static void Run() { // ExStart:AddSVGObject // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Tables(); // Instantiate Document object Document doc = new Document(); // Create an image instance Aspose.Pdf.Image img = new Aspose.Pdf.Image(); // Set image type as SVG img.FileType = Aspose.Pdf.ImageFileType.Svg; // Path for source file img.File = dataDir + "SVGToPDF.svg"; // Set width for image instance img.FixWidth = 50; // Set height for image instance img.FixHeight = 50; // Create table instance Aspose.Pdf.Table table = new Aspose.Pdf.Table(); // Set width for table cells table.ColumnWidths = "100 100"; // Create row object and add it to table instance Aspose.Pdf.Row row = table.Rows.Add(); // Create cell object and add it to row instance Aspose.Pdf.Cell cell = row.Cells.Add(); // Add textfragment to paragraphs collection of cell object cell.Paragraphs.Add(new TextFragment("First cell")); // Add another cell to row object cell = row.Cells.Add(); // Add SVG image to paragraphs collection of recently added cell instance cell.Paragraphs.Add(img); // Create page object and add it to pages collection of document instance Page page = doc.Pages.Add(); // Add table to paragraphs collection of page object page.Paragraphs.Add(table); dataDir = dataDir + "AddSVGObject_out.pdf"; // Save PDF file doc.Save(dataDir); // ExEnd:AddSVGObject Console.WriteLine("\nSVG image added successfully inside a table cell.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:ImageToPDF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Instantiate Document Object Document doc = new Document(); // Add a page to pages collection of document Page page = doc.Pages.Add(); // Load the source image file to Stream object FileStream fs = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open, FileAccess.Read); byte[] tmpBytes = new byte[fs.Length]; fs.Read(tmpBytes, 0, int.Parse(fs.Length.ToString())); MemoryStream mystream = new MemoryStream(tmpBytes); // Instantiate BitMap object with loaded image stream Bitmap b = new Bitmap(mystream); // Set margins so image will fit, etc. page.PageInfo.Margin.Bottom = 0; page.PageInfo.Margin.Top = 0; page.PageInfo.Margin.Left = 0; page.PageInfo.Margin.Right = 0; page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height); // Create an image object Aspose.Pdf.Image image1 = new Aspose.Pdf.Image(); // Add the image into paragraphs collection of the section page.Paragraphs.Add(image1); // Set the image file stream image1.ImageStream = mystream; dataDir = dataDir + "ImageToPDF_out.pdf"; // Save resultant PDF file doc.Save(dataDir); // Close memoryStream object mystream.Close(); // ExEnd:ImageToPDF Console.WriteLine("\nImage converted to pdf successfully.\nFile saved at " + dataDir); }
private Document InsertImage(Document document, string barcodeImagePath) { // get page from Pages collection of PDF file Aspose.Pdf.Page page = document.Pages[1]; // create an image instance Aspose.Pdf.Image img = new Aspose.Pdf.Image(); img.IsInLineParagraph = true; // set Image Width and Height in Points img.FixWidth = 100; img.FixHeight = 100; img.HorizontalAlignment = HorizontalAlignment.Right; img.VerticalAlignment = VerticalAlignment.Top; // set image type as SVG img.FileType = Aspose.Pdf.ImageFileType.Unknown; // path for source barcode image file img.File = barcodeImagePath; page.Paragraphs.Add(img); // return updated PDF document return(document); }
public static void Run() { // ExStart:TextAndImageAsParagraph // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Instantiate Document instance Document doc = new Document(); // Add page to pages collection of Document instance Page page = doc.Pages.Add(); // Create TextFragmnet TextFragment text = new TextFragment("Hello World.. "); // Add text fragment to paragraphs collection of Page object page.Paragraphs.Add(text); // Create an image instance Aspose.Pdf.Image image = new Aspose.Pdf.Image(); // Set image as inline paragraph so that it appears right after // The previous paragraph object (TextFragment) image.IsInLineParagraph = true; // Specify image file path image.File = dataDir + "aspose-logo.jpg"; // Set image Height (optional) image.FixHeight = 30; // Set Image Width (optional) image.FixWidth = 100; // Add image to paragraphs collection of page object page.Paragraphs.Add(image); // Re-initialize TextFragment object with different contents text = new TextFragment(" Hello Again.."); // Set TextFragment as inline paragraph text.IsInLineParagraph = true; // Add newly created TextFragment to paragraphs collection of page page.Paragraphs.Add(text); dataDir = dataDir + "TextAndImageAsParagraph_out_.pdf"; doc.Save(dataDir); // ExEnd:TextAndImageAsParagraph Console.WriteLine("\nText and image added successfully as an inline paragraphs.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:TextAndImageAsParagraph // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Instantiate Document instance Document doc = new Document(); // Add page to pages collection of Document instance Page page = doc.Pages.Add(); // Create TextFragmnet TextFragment text = new TextFragment("Hello World.. "); // Add text fragment to paragraphs collection of Page object page.Paragraphs.Add(text); // Create an image instance Aspose.Pdf.Image image = new Aspose.Pdf.Image(); // Set image as inline paragraph so that it appears right after // The previous paragraph object (TextFragment) image.IsInLineParagraph = true; // Specify image file path image.File = dataDir + "aspose-logo.jpg"; // Set image Height (optional) image.FixHeight = 30; // Set Image Width (optional) image.FixWidth = 100; // Add image to paragraphs collection of page object page.Paragraphs.Add(image); // Re-initialize TextFragment object with different contents text = new TextFragment(" Hello Again.."); // Set TextFragment as inline paragraph text.IsInLineParagraph = true; // Add newly created TextFragment to paragraphs collection of page page.Paragraphs.Add(text); dataDir = dataDir + "TextAndImageAsParagraph_out.pdf"; doc.Save(dataDir); // ExEnd:TextAndImageAsParagraph Console.WriteLine("\nText and image added successfully as an inline paragraphs.\nFile saved at " + dataDir); }
/// <summary> /// /// </summary> private void StartBATCH_CIF() { Form1.BATCH_CaseIDTimerFlag = true; Utility utility = null; string strSql = string.Empty; List <IDataParameter> para = null; DataTable dt = null; //todo 確認是否需要先複制再合檔? //string file_temp_dir_path = Path.Combine(ConfigPath.TempDirPath, Guid.NewGuid().ToString()); try { utility = new Utility(); this.InitLog("BATCH_CIF"); if (utility.XDocSetting == null) { this.WriteLog(Mode.LogMode.ERROR, string.Format("沒有設定檔")); return; } //string last_working_time = (string)utility.XDocSetting.Root.Descendants("Timer").Where(x => (string)x.Element("name") == "Batch").FirstOrDefault().Element("lastWorkingTime"); //bool check_working = String.IsNullOrEmpty(last_working_time); //if (!check_working) //{ // check_working = !DateTime.Parse(last_working_time).ToString("yyyyMMdd").Equals(DateTime.Now.AddSeconds(this.BATCH_CaseIDTimer_Interval / 1000).ToString("yyyyMMdd")); //} //if (check_working) //{ // string startTime = (string)utility.XDocSetting.Root.Descendants("Timer").Where(x => (string)x.Element("name") == "Batch").FirstOrDefault().Element("start"); // if (String.IsNullOrEmpty(startTime) || startTime.Length != 4) throw new Exception(string.Format("每日固定執行時間設定錯誤")); // DateTime working_time = DateTime.Parse(string.Format("{0} {1}:{2}:00", DateTime.Now.ToString("yyyy/MM/dd"), startTime.Substring(0, 2), startTime.Substring(2, 2))); // this.WriteLog(Mode.LogMode.INFO, string.Format("預計開始執行時間:{0}", working_time.ToString("yyyy/MM/dd HH:mm:ss"))); // TimeSpan ts = DateTime.Now - working_time; // check_working = ts.TotalSeconds >= 0 && ts.TotalSeconds <= (this.BATCH_CaseIDTimer_Interval / 1000); // this.WriteLog(Mode.LogMode.INFO, string.Format("比對時間結果:{0},{1}", check_working ? "準備開始" : "時間未到", ts.TotalSeconds.ToString())); //} //if (!check_working) return; DateTime start_date = DateTime.Now.AddDays(-1); this.WriteLog(Mode.LogMode.INFO, string.Format("準備執行 {0} 的作業", start_date.ToString("yyyy/MM/dd"))); strSql = utility.Select.BATCH_CIF_INFO(start_date.ToString("yyyy/MM/dd 00:00:00"), start_date.ToString("yyyy/MM/dd 23:59:59"), start_date.ToString("yyyyMM"), ref para); #region SQL Debug this.WriteLog(Log.Mode.LogMode.DEBUG, strSql); this.WriteLog(Log.Mode.LogMode.DEBUG, para.ToLog()); #endregion dt = utility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para); this.WriteLog(Mode.LogMode.INFO, string.Format("共有{0}筆資料", dt.Rows.Count)); if (dt.Rows.Count.Equals(0)) { this.WriteLastWorkingTime(utility); return; } string message = string.Empty; var query = from batch in dt.AsEnumerable() select new { CREATE_DATETIME = batch.Field <DateTime>("CREATE_DATETIME"), SESSION_KEY = batch.Field <string>("SESSION_KEY"), TXN_DATE = batch.Field <DateTime>("TXN_DATE"), TXN_ACCOUNT = batch.Field <string>("TXN_ACCOUNT"), BRANCH_ID = batch.Field <string>("BRANCH_ID"), FILE_ID = batch.Field <string>("FILE_ID"), FILE_CREATE_DATETIME = batch.Field <DateTime>("CREATE_DATETIME"), FILE_SEQ = batch.Field <Int16>("FILE_SEQ"), FILE_ROOT = batch.Field <string>("FILE_ROOT"), FILE_PATH = batch.Field <string>("FILE_PATH"), PDF = batch.Field <string>("PDF"), FILE_TYPE = batch.Field <Int16>("FILE_TYPE"), T_MNEMONIC = batch.Field <string>("T_MNEMONIC"), T_EMAIL_SIGN_1 = batch.Field <string>("T_EMAIL_SIGN_1"), T_EMAIL_1 = batch.Field <string>("T_EMAIL_1") }; var queryG = query.GroupBy(o => o.T_MNEMONIC); Aspose.Pdf.License licenseWordsTxt = new Aspose.Pdf.License(); licenseWordsTxt.SetLicense("Aspose.Pdf.lic"); //if (!Directory.Exists(file_temp_dir_path)) Directory.CreateDirectory(file_temp_dir_path); string txt_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}.txt", start_date.ToString("yyyyMMdd"))); txt_file_path.DeleteSigleFile(); StreamWriter streamWriter = new StreamWriter(txt_file_path); foreach (var item in queryG) { this.WriteLog(Log.Mode.LogMode.INFO, string.Format("準備產生{0}", item.Key)); Document doc = new Document(); string pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_001.pdf", start_date.ToString("yyyyMMdd"), item.Key)); string content = string.Empty; string cif_ID = string.Empty; //if (!File.Exists(pdf_file_path)) { long pdfFileSize = 0; bool isPDFSizeTooLength = false; int fileNameCount = 1; foreach (var batch in item) { try { utility.DBLog(SysCode.A010, "Batch", batch.T_MNEMONIC, string.Format("開始產生PDF:{0}", Path.GetFileNameWithoutExtension(pdf_file_path))); string file_root = batch.FILE_ROOT; string file_path = batch.FILE_PATH; string file_full_path = file_root.FilePathCombine(file_path); bool exists = File.Exists(file_full_path); if (!exists) { this.WriteLog(Log.Mode.LogMode.ERROR, message = string.Format("SESSION_KEY:{0},CIF_ID:{1},FILE_ID:{2}::檔案不存在({3})", batch.SESSION_KEY, batch.T_MNEMONIC, batch.FILE_ID, file_full_path)); continue; } switch (batch.T_MNEMONIC.Length) { case 9: case 11: cif_ID = batch.T_MNEMONIC.Substring(0, batch.T_MNEMONIC.Length - 2); break; default: cif_ID = batch.T_MNEMONIC; break; } // Load the source image file to Stream object FileStream fs = new FileStream(file_full_path, FileMode.Open, FileAccess.Read); pdfFileSize += fs.Length; byte[] tmpBytes = new byte[fs.Length]; fs.Read(tmpBytes, 0, int.Parse(fs.Length.ToString())); MemoryStream mystream = new MemoryStream(tmpBytes); // Instantiate BitMap object with loaded image stream Bitmap b = new Bitmap(mystream); // Add a page to pages collection of document Page page = doc.Pages.Add(); // Set margins so image will fit, etc. page.PageInfo.Margin.Bottom = 0; page.PageInfo.Margin.Top = 0; page.PageInfo.Margin.Left = 0; page.PageInfo.Margin.Right = 0; page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height); // Create an image object Aspose.Pdf.Image image1 = new Aspose.Pdf.Image(); // Add the image into paragraphs collection of the section page.Paragraphs.Add(image1); // Set the image file stream image1.ImageStream = mystream; image1.ImageScale = 0.95F; //大於9M的要先存檔 if (pdfFileSize > 9437184) { pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_{2}.pdf", start_date.ToString("yyyyMMdd"), item.Key, fileNameCount.ToString().PadLeft(3, '0'))); this.WriteLog(Log.Mode.LogMode.DEBUG, string.Format("pdfFileSize:{0}、pdf_file_path:{1}", pdfFileSize, pdf_file_path)); content = Path.GetFileNameWithoutExtension(pdf_file_path) + ":" + cif_ID + ":" + batch.T_EMAIL_1 + ":" + batch.TXN_DATE.ToString("yyyyMMdd"); pdf_file_path.DeleteSigleFile(); doc.Encrypt("23113343", "23113343", 0, CryptoAlgorithm.AESx128); doc.Save(pdf_file_path); mystream.Close(); doc.Pages.Clear(); doc.Dispose(); doc = null; doc = new Document(); streamWriter.WriteLine(content); fileNameCount += 1; pdfFileSize = 0; isPDFSizeTooLength = true; } else { isPDFSizeTooLength = false; content = Path.GetFileNameWithoutExtension(pdf_file_path) + ":" + cif_ID + ":" + batch.T_EMAIL_1 + ":" + batch.TXN_DATE.ToString("yyyyMMdd"); } } catch (System.Exception ex) { this.WriteLog(Log.Mode.LogMode.ERROR, ex.ToString()); utility.DBLog(SysCode.E013, "Batch", batch.T_MNEMONIC, string.Format("{0}::{1}", Path.GetFileNameWithoutExtension(pdf_file_path), ex.Message)); } } if (!isPDFSizeTooLength) { pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_{2}.pdf", start_date.ToString("yyyyMMdd"), item.Key, fileNameCount.ToString().PadLeft(3, '0'))); pdf_file_path.DeleteSigleFile(); doc.Encrypt("23113343", "23113343", 0, CryptoAlgorithm.AESx128); doc.Save(pdf_file_path); doc.Dispose(); streamWriter.WriteLine(content); } } //else this.WriteLog(Log.Mode.LogMode.INFO, string.Format("已存在於準備上傳,將略過 ({0})", pdf_file_path)); } streamWriter.Close(); this.WriteLastWorkingTime(utility); } catch (System.Exception ex) { this.WriteLog(Log.Mode.LogMode.ERROR, ex.ToString()); this.WriteLog(Mode.LogMode.INFO, string.Format("將於{0}秒後重試", this.BATCH_CaseIDTimer.Interval / 1000)); } finally { if (utility != null) { utility.CloseConn(); utility = null; } dt = null; para = null; GC.Collect(); GC.WaitForPendingFinalizers(); Form1.BATCH_CaseIDTimerFlag = false; } }
private void CreatePDFWithTable() { String inFile = myDir + "sample.pdf"; Random rand = new Random(); String outFile = myDir + rand.Next(1000, 10000) + ".pdf"; Document pdfDoc = new Document(inFile); RemoveHeader(pdfDoc); RemoveFooter(pdfDoc); Table table = new Table(); table.Border = new BorderInfo(BorderSide.All, 0.1F); var margin = new MarginInfo { Top = 0f, Left = 0f, Right = 0f, Bottom = 0f }; table.Margin = margin; double pageWidth = pdfDoc.Pages[1].PageInfo.Width; int columnWidth = ((int)pageWidth) / 2; table.ColumnWidths = columnWidth + " " + columnWidth; Row row1 = new Row(); var cell1 = new Cell(); cell1.ColSpan = 2; TextFragment text1 = new TextFragment("!!!!!!!! This is a sample footer overwritten"); text1.Margin.Bottom = 2; text1.Margin.Top = 2; text1.Margin.Right = 2; text1.Margin.Left = 2; text1.TextState.Font = FontRepository.FindFont("Verdana"); text1.TextState.FontSize = 12; cell1.Paragraphs.Add(text1); row1.Cells.Add(cell1); table.Rows.Add(row1); Row row2 = new Row(); Cells cells2 = new Cells(); //add text cells2.Add("Row 2"); //add logo Aspose.Pdf.Image img = new Aspose.Pdf.Image(); img.File = myDir + "Panda.png"; // img2.File = myDir + "images.png"; img.FixWidth = 78; img.FixHeight = 31; Cell cell2 = row2.Cells.Add(); cell2.Paragraphs.Add(img); cells2.Add(cell2); row2.Cells = cells2; table.Rows.Add(row2); Table tableHeader = new Table(); tableHeader.Border = new BorderInfo(BorderSide.All, 0.1F); var margin1 = new MarginInfo { Top = 0f, Left = 0f, Right = 0f, Bottom = 0f }; tableHeader.Margin = margin1; double pageWidth1 = pdfDoc.Pages[1].PageInfo.Width; int columnWidth1 = ((int)pageWidth) / 2; tableHeader.ColumnWidths = columnWidth + " " + columnWidth; Row row3 = new Row(); var cell3 = new Cell(); cell1.ColSpan = 2; TextFragment text2 = new TextFragment(" This is a sample Header overwritten....!"); text2.Margin.Bottom = 2; text2.Margin.Top = 2; text2.Margin.Right = 2; text2.Margin.Left = 2; text2.TextState.Font = FontRepository.FindFont("Verdana"); text2.TextState.FontSize = 12; cell3.Paragraphs.Add(text2); row3.Cells.Add(cell3); tableHeader.Rows.Add(row3); Row row4 = new Row(); Cells cells4 = new Cells(); //add text cells4.Add("Row 1"); //add logo Aspose.Pdf.Image img2 = new Aspose.Pdf.Image(); //img.File = myDir + "Panda.png"; img2.File = myDir + "images.png"; img2.FixWidth = 78; img2.FixHeight = 31; Cell cells5 = row4.Cells.Add(); cells5.Paragraphs.Add(img2); cells4.Add(cells5); row4.Cells = cells4; tableHeader.Rows.Add(row4); // creating a header HeaderFooter header = new HeaderFooter(); var marginheader = new MarginInfo { Top = 0f, Left = 10f, Right = 10f, Bottom = 0f }; header.Margin = marginheader; header.Paragraphs.Add(tableHeader); // creating a footer HeaderFooter footer = new HeaderFooter(); var marginFooter = new MarginInfo { Top = 0f, Left = 10f, Right = 10f, Bottom = 0f }; footer.Margin = marginFooter; footer.Paragraphs.Add(table); for (int i = 1; i <= pdfDoc.Pages.Count; i++) { pdfDoc.Pages[i].Header = header; pdfDoc.Pages[i].Footer = footer; pdfDoc.ProcessParagraphs(); } pdfDoc.Save(outFile); }
private TextSegment getTextSegment(HNode node, TextState parentTextState) { TextSegment textSegment = null; // Text element if (node is HNodeText) { textSegment = new TextSegment(); textSegment.TextState = parentTextState; textSegment.Text = (node as HNodeText).Text; if (hyperlinkNode != null) { Aspose.Pdf.WebHyperlink pdfHyperlink = new WebHyperlink(hyperlinkNode.GetAttribute("href", "#")); textSegment.Hyperlink = pdfHyperlink; } } // New Line element <br /> if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.br) { /* * //слетают стили!!! * textSegment = new TextSegment(); * //textSegment.TextState = parentTextState; * textSegment.Text = Environment.NewLine; */ pdfNewLine = new TextSegment(); pdfNewLine.Text = Environment.NewLine; } // Hyperlink element <a> if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.a) { PUtil.TextStateUtil.TextState_ModifyForHyperlink(parentTextState); PUtil.TextStateUtil.TextState_ModifyFromHStyles((node as HNodeTag).Styles, parentTextState); } // Bold text element <b> if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.b) { PUtil.TextStateUtil.TextState_ModifyForBold(parentTextState); PUtil.TextStateUtil.TextState_ModifyFromHStyles((node as HNodeTag).Styles, parentTextState); } // Italic text element <i> if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.i) { PUtil.TextStateUtil.TextState_ModifyForItalic(parentTextState); PUtil.TextStateUtil.TextState_ModifyFromHStyles((node as HNodeTag).Styles, parentTextState); } // Image element <img> if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.img) { pdfImage = getImage(node as HNodeTag); } // Form field element <input> if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.input) { pdfFormField = getFormField(node as HNodeTag); } // Button element <button> if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.button) { pdfFormField = getFormFieldButton(node as HNodeTag); } // TODO - other inline tags return(textSegment); }
public void GeneratePDF(ReceivedLetter receivedLetter) { MemoryStream stream = null; if (receivedLetter.ReceiveLetterFiles != null && receivedLetter.ReceiveLetterFiles.Count > 0) { //Render Letter Content With Files Aspose.Pdf.Document contentPdf = new Aspose.Pdf.Document(); foreach (var file in receivedLetter.ReceiveLetterFiles) { if (file.File.ContentType.Contains("image")) { Aspose.Pdf.Page page = contentPdf.Pages.Add(); Bitmap b = new Bitmap(new MemoryStream(file.File.Content)); page.PageInfo.Width = b.Width; page.PageInfo.Height = b.Height; // Set margins so image will fit, etc. page.PageInfo.Margin.Bottom = 0; page.PageInfo.Margin.Top = 0; page.PageInfo.Margin.Left = 0; page.PageInfo.Margin.Right = 0; page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height); Aspose.Pdf.Image image1 = new Aspose.Pdf.Image(); // Add the image into paragraphs collection of the section page.Paragraphs.Add(image1); // Set the image file stream image1.ImageStream = new MemoryStream(file.File.Content); } else if (file.File.ContentType.Contains("pdf")) { //Append pdf to appendages Aspose.Pdf.Document thisPDF = new Aspose.Pdf.Document(new MemoryStream(file.File.Content)); contentPdf.Pages.Add(thisPDF.Pages); } else if (file.File.ContentType.Contains("word")) { //Convert to pdf first Document thisDoc = new Document(new MemoryStream(file.File.Content)); MemoryStream temp = new MemoryStream(); thisDoc.Save(temp, SaveFormat.Pdf); //Second append it to appendages Aspose.Pdf.Document thisPDF = new Aspose.Pdf.Document(temp); contentPdf.Pages.Add(thisPDF.Pages); } } stream = new MemoryStream(); contentPdf.Save(stream); receivedLetter.LetterFileContent = stream.ToArray(); } else { receivedLetter.LetterFileContent = new byte[0]; } //Debug //Aspose.Pdf.Document letterFile = new Aspose.Pdf.Document(stream); //letterFile.Save(Server.MapPath("~/LetterOnly.pdf")); //Save letter with Appendage if (receivedLetter.Appendages != null && receivedLetter.Appendages.Count > 0) { Aspose.Pdf.Document appendagePdf = new Aspose.Pdf.Document(); foreach (var file in receivedLetter.Appendages) { if (file.File.ContentType.Contains("image")) { Page page = appendagePdf.Pages.Add(); Bitmap b = new Bitmap(new MemoryStream(file.File.Content)); page.PageInfo.Width = b.Width; page.PageInfo.Height = b.Height; // Set margins so image will fit, etc. page.PageInfo.Margin.Bottom = 0; page.PageInfo.Margin.Top = 0; page.PageInfo.Margin.Left = 0; page.PageInfo.Margin.Right = 0; page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height); Aspose.Pdf.Image image1 = new Aspose.Pdf.Image(); // Add the image into paragraphs collection of the section page.Paragraphs.Add(image1); // Set the image file stream image1.ImageStream = new MemoryStream(file.File.Content); } else if (file.File.ContentType.Contains("pdf")) { //Append pdf to appendages Aspose.Pdf.Document thisPDF = new Aspose.Pdf.Document(new MemoryStream(file.File.Content)); appendagePdf.Pages.Add(thisPDF.Pages); } else if (file.File.ContentType.Contains("word")) { //Convert to pdf first Document thisDoc = new Document(new MemoryStream(file.File.Content)); MemoryStream temp = new MemoryStream(); thisDoc.Save(temp, SaveFormat.Pdf); //Second append it to appendages Aspose.Pdf.Document thisPDF = new Aspose.Pdf.Document(temp); appendagePdf.Pages.Add(thisPDF.Pages); } } //Return PDF from letter if (stream != null && receivedLetter.LetterFileContent.Length > 0) { Aspose.Pdf.Document letterPdf = new Aspose.Pdf.Document(stream); stream = new MemoryStream(); appendagePdf.Save(stream); receivedLetter.AppendageContent = stream.ToArray(); //Debug //appendagePdf.Save(Server.MapPath("~/AppendagesOnly.pdf")); letterPdf.Pages.Add(appendagePdf.Pages); stream = new MemoryStream(); letterPdf.Save(stream); //Debug //letterPdf.Save(Server.MapPath("~/letterWithAppendages.pdf")); receivedLetter.LetterFileAppendageContent = stream.ToArray(); } else { stream = new MemoryStream(); appendagePdf.Save(stream); receivedLetter.AppendageContent = stream.ToArray(); receivedLetter.LetterFileAppendageContent = stream.ToArray(); } } else { receivedLetter.LetterFileAppendageContent = new byte[0]; receivedLetter.AppendageContent = new byte[0]; } }
private void createNode(HNode node, TextState parentTextState) { TextState nodeTextState = new TextState(); nodeTextState.ApplyChangesFrom(parentTextState); if (node is HNodeTag) { PUtil.TextStateUtil.TextState_ModifyFromHStyles((node as HNodeTag).Styles, nodeTextState); } // Block element if ((node is HNodeTag) && HUtil.TagUtil.IsBlockTag((node as HNodeTag).TagType)) { addTextFragmentOnPage(); createTextFragmentByTagType((node as HNodeTag).TagType); } // Inline element or Text element else if ( (node is HNodeTag) && HUtil.TagUtil.IsInlineTag((node as HNodeTag).TagType) || (node is HNodeText) ) { if ((node is HNodeText) && (node as HNodeText).ParentNode != null && ((node as HNodeText).ParentNode is HNodeTag) && (((node as HNodeText).ParentNode as HNodeTag)).TagType == HTagType.button) { // } else { // Create TextSegment for element TextSegment textSegment = getTextSegment(node, nodeTextState); // New Line, <BR /> if (pdfNewLine != null) { double marginTop = 0; double marginBottom = 0; if (pdfTextFragment != null) { marginBottom = pdfTextFragment.Margin.Bottom; pdfTextFragment.Margin.Bottom = 0; } addTextFragmentOnPage(); createTextFragmentByTagType(HTagType.div); if (pdfTextFragment != null) { pdfTextFragment.Margin.Top = marginTop; pdfTextFragment.Margin.Bottom = marginBottom; } pdfNewLine = null; } // Image else if (pdfImage != null) { double imageHeight = pdfImage.FixHeight; MarginInfo margin = new MarginInfo(0, 12, 0, 12); if (pdfTextFragment == null || pdfTextFragment.Segments.Count == 0 || (pdfTextFragment.Segments.Count == 1 && pdfTextFragment.Segments[1].Text == String.Empty)) { } else { pdfTextFragment.Margin.Top += imageHeight; margin = new MarginInfo(0, pdfTextFragment.Margin.Bottom, 0, -1 * imageHeight); } addTextFragmentOnPage(false); pdfImage.IsInLineParagraph = true; pdfImage.Margin = margin; inlineParagraphMargin = margin; if (hyperlinkNode != null) { Aspose.Pdf.WebHyperlink pdfHyperlink = new WebHyperlink(hyperlinkNode.GetAttribute("href", "#")); pdfImage.Hyperlink = pdfHyperlink; } pdfPage.Paragraphs.Add(pdfImage); if (node.NextNode == null) { updateCurrentPage(); } pdfImage = null; } // Form Field Element else if (pdfFormField != null) { // // // double inputHeight = pdfFormField.Height; MarginInfo margin = new MarginInfo(0, 12, 0, 12); if (pdfTextFragment == null || pdfTextFragment.Segments.Count == 0 || (pdfTextFragment.Segments.Count == 1 && pdfTextFragment.Segments[1].Text == String.Empty)) { } else { double textFragmentHeight = pdfTextFragment.Rectangle.Height; margin = pdfTextFragment.Margin; pdfTextFragment.Margin.Bottom = textFragmentHeight - inputHeight; pdfTextFragment.Margin.Top += Math.Max(0, (inputHeight - textFragmentHeight)); pdfTextFragment.Margin.Top += inputHeight; } addTextFragmentOnPage(false); pdfFormField.IsInLineParagraph = true; pdfFormField.Margin = margin; inlineParagraphMargin = new MarginInfo(pdfFormField.Width, margin.Bottom, margin.Right, margin.Top); pdfPage.Paragraphs.Add(pdfFormField); if (node.NextNode == null) { updateCurrentPage(); } pdfFormField = null; } // TextFragment for InLineParagraph mode else if (pdfTextFragment == null) { HTagType tagTypeForTextFragment = HTagType.div; bool isInLineParagraphForTextFragment = false; bool flagPreviousImage = false; bool flagPreviousInput = false; if (node.PrevNode != null && (node.PrevNode is HNodeTag) && (node.PrevNode as HNodeTag).TagType == HTagType.img) { // prev image element if (node.ParentNode != null && (node.ParentNode is HNodeTag) && HUtil.TagUtil.IsBlockTag((node.ParentNode as HNodeTag).TagType)) { tagTypeForTextFragment = (node.ParentNode as HNodeTag).TagType; } isInLineParagraphForTextFragment = true; flagPreviousImage = true; } else if (node.PrevNode != null && (node.PrevNode is HNodeTag) && (node.PrevNode as HNodeTag).TagType == HTagType.input) { // prev input element if (node.ParentNode != null && (node.ParentNode is HNodeTag) && HUtil.TagUtil.IsBlockTag((node.ParentNode as HNodeTag).TagType)) { tagTypeForTextFragment = (node.ParentNode as HNodeTag).TagType; } isInLineParagraphForTextFragment = true; flagPreviousInput = true; } else { } createTextFragmentByTagType(tagTypeForTextFragment); pdfTextFragment.IsInLineParagraph = isInLineParagraphForTextFragment; if ((flagPreviousImage || flagPreviousInput) && inlineParagraphMargin != null) { pdfTextFragment.Margin.Top = -1 * pdfTextFragment.Rectangle.Height - inlineParagraphMargin.Bottom; pdfTextFragment.Margin.Bottom = inlineParagraphMargin.Bottom; pdfTextFragment.Margin.Left = inlineParagraphMargin.Left; inlineParagraphMargin = null; } } if (textSegment != null && pdfTextFragment != null) //if (textSegment != null) { pdfTextFragment.Segments.Add(textSegment); } } } // // Create Nodes recursively with consider the hyperlink // if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.a) { hyperlinkNode = (node as HNodeTag); } if (node is HNodeContainer) { foreach (HNode childNode in (node as HNodeContainer).ChildNodes) { createNode(childNode, nodeTextState); } } if ((node is HNodeTag) && (node as HNodeTag).TagType == HTagType.a) { hyperlinkNode = null; } // // // // // Add Text Fragment on Page (if need) // if ((node is HNodeTag) && HUtil.TagUtil.IsBlockTag((node as HNodeTag).TagType)) { addTextFragmentOnPage(); } // // // }