//this function is capable of taking multiple tiff images from a directory //and processing each tiff frame by frame private void AddTiff(Document pdfDocument, iTextSharp.text.Rectangle pdfPageSize, String tiffPath) { RandomAccessFileOrArray ra = new RandomAccessFileOrArray(tiffPath); int pageCount = TiffImage.GetNumberOfPages(ra); for (int i = 1; i <= pageCount; i++) { iTextSharp.text.Image img = TiffImage.GetTiffImage(ra, i); if (img.ScaledWidth > pdfPageSize.Width || img.ScaledHeight > pdfPageSize.Height) { img.SetDpi(2, 2); if (img.DpiX != 0 && img.DpiY != 0 && img.DpiX != img.DpiY) { float percentX = (pdfPageSize.Width * 100) / img.ScaledWidth; float percentY = (pdfPageSize.Height * 100) / img.ScaledHeight; img.ScalePercent(percentX, percentY); img.WidthPercentage = 0; } else { img.ScaleToFit(pdfPageSize.Width, pdfPageSize.Height); } } iTextSharp.text.Rectangle pageRect = new iTextSharp.text.Rectangle(0, 0, img.ScaledWidth, img.ScaledHeight); pdfDocument.SetPageSize(pageRect); pdfDocument.SetMargins(0, 0, 0, 0); pdfDocument.NewPage(); pdfDocument.Add(img); } }
private void extrato_Click(object sender, EventArgs e) { SaveFileDialog salvar = new SaveFileDialog(); salvar.Filter = "PDF Files|*.pdf"; salvar.FilterIndex = 0; string fileName = string.Empty; if (salvar.ShowDialog() == DialogResult.OK) { fileName = salvar.FileName; Document myDocument = new Document(iTextSharp.text.PageSize.A4.Rotate()); PdfWriter.GetInstance(myDocument, new FileStream(fileName, FileMode.Create)); myDocument.Open(); Paragraph p = new Paragraph(); p.Alignment = Element.ALIGN_CENTER; myDocument.Add(new Paragraph("Gráfico Inserido", FontFactory.GetFont("Arial", 60, (int)System.Drawing.FontStyle.Bold))); MemoryStream ms = new MemoryStream(); chart1.SaveImage(ms, ChartImageFormat.Png); iTextSharp.text.Image Chart_Image = iTextSharp.text.Image.GetInstance(ms.ToArray()); Chart_Image.SetDpi(600, 600); Chart_Image.ScaleToFit(200f, 200f); myDocument.Add(Chart_Image); myDocument.Close(); } }
/// <summary> /// 输出图片 /// </summary> /// <param name="bitmapSource"></param> /// <param name="absoluteX"></param> /// <param name="absoluteY"></param> public void PaintImage(Bitmap bitmapSource, float absoluteX, float absoluteY) { ImageFormat imageFormat = ImageFormat.Jpeg; iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(bitmapSource, imageFormat); image.SetDpi(350, 350); float floImageWidth = image.ScaledWidth * DpiScale; float floImageHeight = image.ScaledHeight * DpiScale; image.ScaleToFit(floImageWidth, floImageHeight); image.SetAbsolutePosition(absoluteX, absoluteY); doc.Add(image); }
/// <summary> /// 创建Pdf所需图像 /// </summary> /// <param name="imageBytes"></param> /// <param name="widthS"></param> /// <param name="heightS"></param> /// <returns></returns> private static iTextSharp.text.Image CreatePdfImage(byte[] imageBytes, float widthS = 60f, float heightS = 60f) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes); //图片大小要求统一80x80,需根据实际图片 float perW = (float)Math.Round(widthS / image.Width, 2); float perH = (float)Math.Round(heightS / image.Height, 2); image.ScalePercent(perW * 100, perH * 100); //设置Dpi值,能够清晰些 image.SetDpi(124, 124); return(image); }
public bool EtichettaPdf() { PdfReader reader = new PdfReader(inpFile); int pages = reader.NumberOfPages, pagestw = reader.NumberOfPages + ((coverWMF.Length > 0) ? 1 : 0); logger.DebugFormat("EtichettaPdf..Pages:{0} - Sign:{1}", pages, pagestw); Document document = null; PdfWriter writer = null; PdfContentByte cb = null; PdfImportedPage page; iTextSharp.text.Rectangle rect = null; Chunk chunk = null; Phrase phrase = null; ColumnText ct = null; int rt = 0; try { for (int j = 0; j < pages; j++) { rt = reader.GetPageRotation(j + 1); rect = reader.GetPageSizeWithRotation(j + 1); // if (j == 0) { logger.Debug("Document..add"); document = new Document(rect); writer = PdfWriter.GetInstance(document, new FileStream(outFile, FileMode.Create)); document.Open(); cb = writer.DirectContent; } else { document.SetPageSize(rect); document.NewPage(); } page = writer.GetImportedPage(reader, j + 1); logger.DebugFormat("AddTemplate {0} - {1} - {2} - {3}", j, rt, scalePercent, rect.Width); if (rt == 90) { cb.AddTemplate(page, 0, -1.0F, scalePercent, 0, 0, rect.Height); } else if (rt == 270) { cb.AddTemplate(page, 0, scalePercent, -1f, 0, rect.Width, 0); } else if (rt == 180) { double angle = Math.PI; //Math.sin/cos want in radians switch (rt) { case 90: angle = Math.PI * 90 / 180; break; case 180: angle = Math.PI * 180 / 180; break; case 270: angle = Math.PI * 270 / 180; break; } float a = (float)Math.Cos(angle); float b = (float)Math.Sin(angle); float c = (float)-Math.Sin(angle); float d = (float)Math.Cos(angle); cb.AddTemplate(page, a, b, c, d, rect.Width, rect.Height); } else { cb.AddTemplate(page, 1f, 0, 0, scalePercent, 0, 0); } //cb.AddTemplate(page, 1f, 1f); // put header int pagen = j + 1; string testo = testoEtichetta.Replace("(pagina)", pagen.ToString()); testo = testo.Replace("(pagine)", pagestw.ToString()); string FontName = FontFactory.COURIER; if (string.Compare(FontFace, "HELVETICA", true) == 0) { FontName = FontFactory.HELVETICA; } if (string.Compare(FontFace, "TIMES", true) == 0) { FontName = FontFactory.TIMES; } int style = iTextSharp.text.Font.NORMAL; if (FontStyle.IndexOf("Bold") >= 0) { style |= iTextSharp.text.Font.BOLD; } if (FontStyle.IndexOf("Italic") >= 0) { style |= iTextSharp.text.Font.ITALIC; } chunk = new Chunk(testo, FontFactory.GetFont(FontName, font.SizeInPoints, style, new iTextSharp.text.BaseColor(0, 0, 0))); document.Add(chunk); if (testoFooter.Length > 0) { testo = testoFooter.Replace("(pagina)", pagen.ToString()); testo = testo.Replace("(pagine)", pagestw.ToString()); phrase = new Phrase(); chunk = new Chunk(testo, FontFactory.GetFont(FontName, font.SizeInPoints, style, new iTextSharp.text.BaseColor(0, 0, 0))); phrase.Add(chunk); ct = new ColumnText(cb); ct.SetSimpleColumn(phrase, 40, 10, rect.Right, 0, 0, Element.ALIGN_LEFT); ct.Go(); } cb.Stroke(); } if (coverWMF.Length > 0) // retro copertina con le firme { string wmfFile = Path.Combine(Path.GetTempPath(), "SC_" + Guid.NewGuid() + ".tmp"); try { FileStream fs = new FileStream(wmfFile + ".EMF", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(coverWMF, 0, coverWMF.Length); fs.Close(); using (Metafile mf = new Metafile(wmfFile + ".EMF")) { mf.Save(wmfFile + ".WMF", ImageFormat.Emf); } iTextSharp.text.Image wmf = iTextSharp.text.Image.GetInstance(wmfFile + ".WMF"); //wmf.SetAbsolutePosition(10f, 550f); //wmf.ScaleToFit(400, 550); //wmf.SetDpi(300, 300); wmf.SetAbsolutePosition(30f, 300f); wmf.ScaleToFit(400, 550); wmf.SetDpi(300, 300); document.NewPage(); // label string testo = testoEtichetta.Replace("(pagina)", pagestw.ToString()); testo = testo.Replace("(pagine)", pagestw.ToString()); string FontName = FontFactory.COURIER; if (string.Compare(FontFace, "HELVETICA", true) == 0) { FontName = FontFactory.HELVETICA; } if (string.Compare(FontFace, "TIMES", true) == 0) { FontName = FontFactory.TIMES; } int style = iTextSharp.text.Font.NORMAL; if (FontStyle.IndexOf("Bold") >= 0) { style |= iTextSharp.text.Font.BOLD; } if (FontStyle.IndexOf("Italic") >= 0) { style |= iTextSharp.text.Font.ITALIC; } chunk = new Chunk(testo, FontFactory.GetFont(FontName, font.SizeInPoints, style, new iTextSharp.text.BaseColor(0, 0, 0))); document.Add(chunk); document.Add(wmf); if (testoFooter.Length > 0) { testo = testoFooter.Replace("(pagina)", pagestw.ToString()); testo = testo.Replace("(pagine)", pagestw.ToString()); phrase = new Phrase(); chunk = new Chunk(testo, FontFactory.GetFont(FontName, font.SizeInPoints, style, new iTextSharp.text.BaseColor(0, 0, 0))); phrase.Add(chunk); ct = new ColumnText(cb); ct.SetSimpleColumn(phrase, 40, 10, rect.Right, 0, 0, Element.ALIGN_LEFT); ct.Go(); } } catch (Exception exp) { throw new Exception(exp.Message + " " + exp.StackTrace); } File.Delete(wmfFile); File.Delete(wmfFile + ".WMF"); File.Delete(wmfFile + ".EMF"); } } finally { if (reader != null) { reader.Close(); } document.Close(); } return(true); }
private void btnExport_Click(object sender, EventArgs e) { saveFileDialog1.Title = "Export to PDF"; saveFileDialog1.Filter = "(*.pdf)|*.pdf"; saveFileDialog1.InitialDirectory = @"D:\"; saveFileDialog1.FileName = "AHP_" + mainForm.getCurrentTopic().topicName + "_" + mainForm.getCurrentUser().userName; saveFileDialog1.FileOk += saveFileDialog1_FileOk; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { try { iTextSharp.text.Document doc = new iTextSharp.text.Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName, FileMode.Create)); //pdfWriter.PageEvent = new ITextEvents(mainForm.getCurrentTopic().topicName.ToUpper()); // FONT DEFINITION //iTextSharp.text.pdf.BaseFont bfTitle = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED); //iTextSharp.text.Font fontTitle = new iTextSharp.text.Font(bfTitle, 15); //fontTitle.SetStyle(iTextSharp.text.Font.UNDERLINE); iTextSharp.text.pdf.BaseFont bfNormal = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED); iTextSharp.text.pdf.BaseFont bfBold = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED); iTextSharp.text.Font fontSubtitle = new iTextSharp.text.Font(bfBold, 13); iTextSharp.text.Font fontColHeader = new iTextSharp.text.Font(bfBold, 11); iTextSharp.text.Font fontTable = new iTextSharp.text.Font(bfNormal, 10); iTextSharp.text.Font fontConclusion = new iTextSharp.text.Font(bfNormal, 10); fontConclusion.SetStyle(iTextSharp.text.Font.UNDERLINE); // HEADER AND FOOTER TwoColumnHeaderFooter PageEventHandler = new TwoColumnHeaderFooter(mainForm.getCurrentUser().userName); pdfWriter.PageEvent = PageEventHandler; PageEventHandler.Title = "AHP RESULT"; PageEventHandler.HeaderFont = FontFactory.GetFont(BaseFont.COURIER_BOLD, 10, iTextSharp.text.Font.BOLD); PageEventHandler.HeaderLeft = "Topic"; PageEventHandler.HeaderRight = mainForm.getCurrentTopic().topicName.ToUpper(); doc.Open(); // TITLE //Paragraph title = new Paragraph(mainForm.getCurrentTopic().topicName.ToUpper(), fontTitle); //title.Alignment = Element.ALIGN_CENTER; //doc.Add(title); doc.Add(new Paragraph(" ")); // SUBTITLE: DETAIL ALTERNATIVE Paragraph subtitle1 = new Paragraph("DETAIL ALTERNATIVE", fontSubtitle); subtitle1.Alignment = Element.ALIGN_CENTER; subtitle1.SpacingBefore = 25; subtitle1.SpacingAfter = 20; doc.Add(subtitle1); // TABLE DETAIL bool switchCloseAlternativeListForm = true; AlternativeListForm alternativeListForm = null; if (mainForm.isFormOpened(typeof(AlternativeListForm)) != null) { switchCloseAlternativeListForm = false; alternativeListForm = (AlternativeListForm)mainForm.isFormOpened(typeof(AlternativeListForm)); alternativeListForm.MdiParent = mainForm; alternativeListForm.Show(); } else { alternativeListForm = mainForm.getAlternativeListForm(); } DataGridView dataGridView = alternativeListForm.getDGV(); PdfPTable pdfPTable = new PdfPTable(dataGridView.ColumnCount); // Header Column foreach (DataGridViewColumn column in dataGridView.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, fontColHeader)); //cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_MIDDLE; pdfPTable.AddCell(cell); } // Adding DataRow foreach (DataGridViewRow row in dataGridView.Rows) { foreach (DataGridViewCell cell in row.Cells) { PdfPCell pdfPCell = new PdfPCell(new Phrase(cell.Value.ToString(), fontTable)); pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; pdfPTable.AddCell(pdfPCell); } } doc.Add(pdfPTable); mainForm.refreshAllChildrenForm(); if (switchCloseAlternativeListForm) { alternativeListForm.Close(); } // SUBTITLE: COMPARISON Paragraph subtitle2 = new Paragraph("COMPARISON", fontSubtitle); subtitle2.Alignment = Element.ALIGN_CENTER; subtitle2.SpacingBefore = 25; doc.Add(subtitle2); // CHART IMAGE MemoryStream ms = new MemoryStream(); chart1.SaveImage(ms, ChartImageFormat.Png); iTextSharp.text.Image chart_img = iTextSharp.text.Image.GetInstance(ms.ToArray()); chart_img.SetDpi(300, 300); chart_img.ScaleToFit(300f, 300f); chart_img.Alignment = Element.ALIGN_CENTER; doc.Add(chart_img); // SUBTITLE: CONCLUSION Paragraph subtitle3 = new Paragraph("CONCLUSION", fontSubtitle); subtitle3.Alignment = Element.ALIGN_CENTER; subtitle3.SpacingBefore = 25; doc.Add(subtitle3); // CONCLUSION List <List <string> > conclusion = resultController.conclusionBestWorst(currentTopicId); if (conclusion == null) { doc.Add(new Paragraph("Cannot conclude anything, since the data is all the same.", fontTable)); } else { // SUB SUBTITLE BEST ALTERNATIVE Paragraph subtitleBest = new Paragraph("Best Alternative(s)", fontConclusion); subtitleBest.SpacingBefore = 10; subtitleBest.SpacingAfter = 5; subtitleBest.Alignment = Element.ALIGN_CENTER; doc.Add(subtitleBest); int numbering = 1; foreach (List <string> conc in conclusion) { if (conc[0] == "Best") { string oneLine = /*numbering + ". " +*/ conc[1] + " (Best criteria: "; foreach (string crit in resultController.bestWorstCriteria(currentTopicId, conc)) { oneLine += crit + ", "; } Paragraph text = new Paragraph(oneLine.Substring(0, oneLine.Length - 2) + ")\n", fontTable); text.Alignment = Element.ALIGN_CENTER; doc.Add(text); numbering++; } } // SUB SUBTITLE WORST ALTERNATIVE Paragraph subtitleWorst = new Paragraph("Worst Alternative(s)", fontConclusion); subtitleWorst.SpacingBefore = 10; subtitleWorst.SpacingAfter = 5; subtitleWorst.Alignment = Element.ALIGN_CENTER; doc.Add(subtitleWorst); numbering = 1; foreach (List <string> conc in conclusion) { if (conc[0] == "Worst") { string oneLine = /*numbering + ". " +*/ conc[1] + " (Worst criteria: "; foreach (string crit in resultController.bestWorstCriteria(currentTopicId, conc)) { oneLine += crit + ", "; } Paragraph text = new Paragraph(oneLine.Substring(0, oneLine.Length - 2) + ")\n", fontTable); text.Alignment = Element.ALIGN_CENTER; doc.Add(text); numbering++; } } } doc.Close(); // DIALOG int start = saveFileDialog1.FileName.LastIndexOf('\\') + 1; int length = saveFileDialog1.FileName.Length; var mboxResponse = MessageBox.Show(this, "Successfully exported \"" + saveFileDialog1.FileName.Substring(start, length - start) + "\" to\n" + saveFileDialog1.FileName.Substring(0, start) + "\nDo you want to open the file?", "Export to PDF", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (mboxResponse == DialogResult.Yes) { System.Diagnostics.Process.Start(saveFileDialog1.FileName); } } catch (Exception ex) { MessageBox.Show(this, "An error occured:\n" + ex.Message, "Export to PDF", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } }
public static void SavePDF(bool isHtml, string bookPath, int totalPage, float width, float height, string UserAccount, string bookId, string dbPath, string thumbsPath_Msize, string thumbsPath_Lsize, int counter = 0) { //把參數存起來 if (counter == 0) { PDFFactoryParameter pdfParameter = new PDFFactoryParameter(); pdfParameter.isHtml = isHtml; pdfParameter.bookPath = bookPath; pdfParameter.totalPage = totalPage; pdfParameter.width = width; pdfParameter.height = height; pdfParameter.UserAccount = UserAccount; pdfParameter.bookId = bookId; pdfParameter.dbPath = dbPath; pdfParameter.thumbsPath_Msize = thumbsPath_Msize; pdfParameter.thumbsPath_Lsize = thumbsPath_Lsize; DataTable dt = MSCE.GetDataTable("select ID from FileRow where userid=@1 and id=@2" , UserAccount.Replace("_Sync", "") , bookId); if (dt.Rows.Count > 0) { string ID = dt.Rows[0]["ID"].ToString(); string SQL = @"update FileRow set PDFFactoryParameterJson=@1 where userid=@2 and id=@3"; int success = MSCE.ExecuteNonQuery(SQL , JsonConvert.SerializeObject(pdfParameter) , UserAccount.Replace("_Sync", "") , bookId); if (success < 1) { LogTool.Debug(new Exception(@"DB失敗: " + SQL)); } } } string fileName = System.IO.Path.Combine(bookPath, @"PDFFactory\PDF.pdf"); string PDFFactoryDirectoryName = Path.GetDirectoryName(fileName); string FinalFilePath = System.IO.Path.Combine(bookPath, "PDF.pdf"); Directory.CreateDirectory(PDFFactoryDirectoryName); //using (StreamWriter sw = new StreamWriter(fileName)) //{ //} //File.Create(fileName).Dispose(); //string srcPDF = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pdf.pdf"); //File.Copy(srcPDF, fileName, true); //Thread th = new Thread(()=> Task.Factory.StartNew(() => { try { Singleton_PDFFactory.AddBookInPDFWork(bookId); BookManager bookManager = new BookManager(dbPath); float thinWidth = 0.0f; float thinHeight = 0.0f; float fatWidth = 0.0f; float fatHeight = 0.0f; if (width > height) { fatWidth = width; fatHeight = height; thinWidth = fatHeight; thinHeight = fatWidth; } else { thinWidth = width; thinHeight = height; fatWidth = thinHeight; fatHeight = thinWidth; } iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(width, height); //將圖檔加入到PDF Document myDoc = new Document(rect); FileStream fs = null; //string fileName = System.IO.Path.Combine(bookPath, "PDFFactory/PDF.pdf"); //string PDFFactoryDirectoryName = Path.GetDirectoryName(fileName); //string FinalFilePath = System.IO.Path.Combine(bookPath, "PDF.pdf"); try { fs = new FileStream(fileName, FileMode.Create); PdfWriter writer = PdfWriter.GetInstance(myDoc, fs); string[] files = Directory.GetFiles(PDFFactoryDirectoryName, "*.bmp"); // sort them by creation time Array.Sort <string>(files, delegate(string a, string b) { int fi_a = int.Parse(new FileInfo(a).Name.Split('.')[0]); int fi_b = int.Parse(new FileInfo(b).Name.Split('.')[0]); return(fi_a.CompareTo(fi_b)); }); myDoc.Open(); int i = 0; //Full path to the Unicode Arial file //string fontPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "kaiu.ttf"); ////Create a base font object making sure to specify IDENTITY-H //BaseFont bf = BaseFont.CreateFont(fontPath, // BaseFont.IDENTITY_H, //橫式中文 // BaseFont.NOT_EMBEDDED // ); //Create a specific font object //iTextSharp.text.Font f = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL); string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\..\Fonts\kaiu.ttf"; BaseFont bfChinese = BaseFont.CreateFont( fontPath, BaseFont.IDENTITY_H, //橫式中文 BaseFont.NOT_EMBEDDED ); iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 16f, iTextSharp.text.Font.NORMAL); string pdfPath = ""; if (isHtml == false) { pdfPath = Path.Combine(bookPath, "hyweb"); } else { pdfPath = Path.Combine(bookPath, "data"); } string thumbsPath = ""; //string thumbsPath_Msize = Path.Combine(bookPath, "hyweb", "mthumbs"); //string thumbsPath_Lsize = Path.Combine(bookPath, "hyweb", "mthumbs\\Larger"); if (Directory.Exists(thumbsPath_Lsize) == true) { thumbsPath = thumbsPath_Lsize; } else { thumbsPath = thumbsPath_Msize; } string[] pdfFiles = Directory.GetFiles(pdfPath, "*.pdf"); string pdfPrefix = ""; if (pdfFiles.Length > 0) { string fName = new FileInfo(pdfFiles[0]).Name; pdfPrefix = fName.Split(new char[] { '_' })[0]; } for (int count = 1; count <= totalPage; count++) { try { string pdf = Path.Combine(pdfPath, pdfPrefix + "_" + count + ".pdf"); string thumb; string extension = ".jpg"; if (isHtml == true) { extension = ".png"; } if (isHtml == false) { thumb = Path.Combine(thumbsPath, pdfPrefix + "_" + count + extension); } else { thumb = Path.Combine(thumbsPath, "Slide" + count + extension); } string imgPath = Path.Combine(PDFFactoryDirectoryName, count + ".bmp"); Directory.CreateDirectory(Path.GetDirectoryName(thumb)); if (File.Exists(thumb) == false) { //GhostscriptWrapper.GeneratePageThumbs(pdf, thumb, 1, 1, 96, 96); //consolePDFtoJPG.exe //在背景執行,無DOS視窗閃爍問題 //System.Diagnostics.Process p = new System.Diagnostics.Process(); //p.StartInfo.FileName = "consolePDFtoJPG.exe"; //p.StartInfo.Arguments = string.Format(" {0} {1} " ,pdf,thumb); //p.StartInfo.UseShellExecute = false; //p.StartInfo.RedirectStandardInput = true; //p.StartInfo.RedirectStandardOutput = true; //p.StartInfo.RedirectStandardError = true; //p.StartInfo.CreateNoWindow = true; //p.Start(); } //畫面拍攝 //if (File.Exists(imgPath) == false) //圖形標註 if (1 == 1 || File.Exists(imgPath) == false) { //GetPdfThumbnail(pdf, imgPath); //ConvertPDF2Image(pdf, imgPath, 1, 1, ImageFormat.Bmp, Definition.Ten); if (File.Exists(thumb) == true) { File.Copy(thumb, imgPath, true); } else { //thumb = Path.Combine(thumbsPath_Msize, pdfPrefix + "_" + count + ".jpg"); thumb = Path.Combine(thumbsPath, pdfPrefix + "_" + count + extension); if (File.Exists(thumb) == true) { File.Copy(thumb, imgPath, true); } } } } catch (Exception ex) { LogTool.Debug(ex); } } foreach (string file in files) { try { i++; FileInfo fileInfo = new FileInfo(file); if (fileInfo.Extension.ToLower().Equals(".bmp")) { //myDoc.NewPage(); string cmd = string.Format(@"SELECT page,status,alpha,canvasHeight,canvasWidth,color,points,width FROM bookStrokesDetail as a inner join bookinfo as b on a.userbook_sno=b.sno where bookid='{0}' and page={1} and account='{2}'" , bookId, (i - 1).ToString(), UserAccount); QueryResult rs = bookManager.sqlCommandQuery(cmd); float xWidth = 0; float xHeight = 0; if (rs != null && rs.fetchRow()) { xWidth = rs.getFloat("canvasWidth"); xHeight = rs.getFloat("canvasHeight"); if (xWidth > 0 && xHeight > 0) { if (xWidth > xHeight) { if (fatWidth <= 0 || fatHeight <= 0) { fatWidth = width; fatHeight = height; thinWidth = fatHeight; thinHeight = fatWidth; } } else { if (thinWidth <= 0 || thinHeight <= 0) { thinWidth = width; thinHeight = height; fatWidth = thinHeight; fatHeight = thinWidth; } } } //myDoc.SetPageSize(new iTextSharp.text.Rectangle(xWidth, xHeight)); } //else //{ // if (penMemoCanvasWidth > 0 && penMemoCanvasHeight > 0) // { // if (penMemoCanvasWidth > penMemoCanvasHeight) // { // if (penMemoCanvasWidth <= 0 || penMemoCanvasHeight <= 0) // { // fatWidth = penMemoCanvasWidth; // fatHeight = penMemoCanvasHeight; // thinWidth = fatHeight; // thinHeight = fatWidth; // } // } // else // { // if (penMemoCanvasWidth <= 0 || penMemoCanvasHeight <= 0) // { // thinWidth = penMemoCanvasWidth; // thinHeight = penMemoCanvasHeight; // fatWidth = thinHeight; // fatHeight = thinWidth; // } // } // } //} // //加入影像 iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(file); float WidthRatio = 1; float HeightRatio = 1; if (img.Width > img.Height) { if (fatWidth > 0 && fatHeight > 0) { rect = new iTextSharp.text.Rectangle(fatWidth, fatHeight); } else { rect = new iTextSharp.text.Rectangle(thinHeight, thinWidth); } } else { if (thinWidth > 0 && thinHeight > 0) { rect = new iTextSharp.text.Rectangle(thinWidth, thinHeight); } else { rect = new iTextSharp.text.Rectangle(fatHeight, fatHeight); } } if (xWidth > 0 && xHeight > 0) { WidthRatio = (rect.Width / xWidth); /// (rect.Height / xHeight); HeightRatio = (rect.Height / xHeight); /// (rect.Width / xWidth); } myDoc.SetPageSize(rect); myDoc.NewPage(); img.SetDpi(300, 300); img.ScaleToFit(rect.Width, rect.Height); //img.SetAbsolutePosition(0, rect.Height - img.Height); img.SetAbsolutePosition(0, 0); //if (xWidth > 0 && xHeight > 0) //{ // img.ScaleToFit(xWidth, xHeight); // img.SetAbsolutePosition(0, rect.Height - xHeight); //} //else //{ // img.ScaleToFit(width, height); // //img.SetAbsolutePosition(0, rect.Height - img.Height); // img.SetAbsolutePosition(0, rect.Height - img.Height); //} myDoc.Add(img); //myDoc.Add(new iTextSharp.text.Paragraph("第 " + i.ToString() + " 頁", fontChinese)); //加註記 cmd = string.Format("select notes from booknoteDetail as a inner join bookInfo as b on a.userbook_sno=b.sno where bookid='{0}' and page='{1}' and account='{2}'" , bookId , (i - 1).ToString() , UserAccount); rs = bookManager.sqlCommandQuery(cmd); if (rs != null && rs.fetchRow()) { //myDoc.Add(new iTextSharp.text.Paragraph(rs.getString("notes"), fontChinese)); myDoc.Add(new iTextSharp.text.Paragraph("\r\n")); //myDoc.Add(new Annotation("作者", rs.getString("notes"))); myDoc.Add(new Annotation("註解", rs.getString("notes"))); } //小畫家 cmd = string.Format(@"SELECT page,status,alpha,canvasHeight,canvasWidth,color,points,width FROM bookStrokesDetail as a inner join bookinfo as b on a.userbook_sno=b.sno where bookid='{0}' and page={1} and status='0' and account='{2}'" , bookId , (i - 1).ToString() , UserAccount); try { rs = bookManager.sqlCommandQuery(cmd); } catch (Exception ex) { LogTool.Debug(ex); } if (rs != null) { while (rs.fetchRow()) { //float imgWidth = rs.getFloat("canvasWidth"); //float imgHeight = rs.getFloat("canvasHeight"); //img.ScaleToFit(imgWidth, imgHeight); //myDoc.Add(img); string color = rs.getString("color"); float alpha = rs.getFloat("alpha"); int red = Convert.ToInt32(color.Substring(1, 2), 16); int green = Convert.ToInt32(color.Substring(3, 2), 16); int blue = Convert.ToInt32(color.Substring(5, 2), 16); float PenWidth = rs.getFloat("width"); //PdfContentByte content = writer.DirectContent; //PdfGState state = new PdfGState(); //state.StrokeOpacity = rs.getFloat("alpha"); // Stroke where the red box will be drawn //content.NewPath(); string points = rs.getString("points"); string[] pointsAry = points.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); int ii = 0; float x1 = 0.0f; float y1 = 0.0f; List <float[]> fff = new List <float[]>(); List <float> fList = new List <float>(); foreach (string xy in pointsAry) { ++ii; string x = xy.Split(new char[] { '{', ',', '}' }, StringSplitOptions.RemoveEmptyEntries)[0]; string y = xy.Split(new char[] { '{', ',', '}' }, StringSplitOptions.RemoveEmptyEntries)[1]; //x1 = int.Parse(x); //y1 = int.Parse(y); x1 = int.Parse(x) * WidthRatio; y1 = int.Parse(y) * HeightRatio; //if (ii == 1) // content.MoveTo(x1, y1); //else //{ // content.LineTo(x1, y1); //} fList.Add(x1); fList.Add(rect.Height - y1); } fff.Add(fList.ToArray()); PdfAnnotation annotation = PdfAnnotation.CreateInk(writer, rect, "", fff.ToArray()); annotation.Color = new iTextSharp.text.BaseColor(red, green, blue, int.Parse(alpha.ToString())); annotation.BorderStyle = new PdfBorderDictionary(PenWidth, PdfBorderDictionary.STYLE_SOLID); //隱藏註釋符號 annotation.Flags = PdfAnnotation.FLAGS_PRINT; writer.AddAnnotation(annotation); //content.SetGState(state); //content.SetRGBColorStroke(red, green, blue); //content.SetLineWidth(PenWidth); //content.Stroke(); } } } } catch (Exception ex) { LogTool.Debug(ex); } } myDoc.AddTitle("電子書"); //文件標題 myDoc.AddAuthor("Hyweb"); //文件作者 } catch (Exception ex) { LogTool.Debug(ex); } finally { try { try { if (myDoc.IsOpen()) { myDoc.Close(); } } catch (Exception ex) { LogTool.Debug(ex); } try { if (fs != null) { fs.Dispose(); } } catch (Exception ex) { LogTool.Debug(ex); } } catch (Exception ex) { LogTool.Debug(ex); } } if (File.Exists(fileName) == true) { File.Copy(fileName, FinalFilePath, true); } //Singleton_PDFFactory.RemoveBookInPDFWork(bookId); counter++; if (counter <= 3) { Singleton_PDFFactory.SavePDF(isHtml, bookPath, totalPage, width, height, UserAccount, bookId, thumbsPath_Msize, thumbsPath_Lsize, dbPath, counter); } else { if (File.Exists(fileName) == true) { File.Copy(fileName, FinalFilePath, true); } Singleton_PDFFactory.RemoveBookInPDFWork(bookId); return; } } catch (Exception ex) { LogTool.Debug(ex); if (counter > 3) { AutoClosingMessageBox.Show("轉檔失敗,請稍後再試"); } //Singleton_PDFFactory.RemoveBookInPDFWork(bookId); } }); //th.IsBackground = false; //th.Start(); }