public ScalePercent ( float percent ) : void | ||
percent | float | the scaling percentage |
Résultat | void |
private void AddCover() { try { byte[] cover = WebCrawler.DownloadCover(lnParameters.urlCover); PdfImage pic = PdfImage.GetInstance(cover); if (pic.Height > pic.Width) { //Maximum height is 800 pixels. float percentage = 0.0f; percentage = 700 / pic.Height; pic.ScalePercent(percentage * 100); } else { //Maximum width is 600 pixels. float percentage = 0.0f; percentage = 540 / pic.Width; pic.ScalePercent(percentage * 100); } pic.Border = Rectangle.BOX; pic.BorderColor = BaseColor.BLACK; pic.BorderWidth = 3f; pdf.NewPage(); pdf.Add(pic); } catch (CoverException) {} }
private void SaveBitmaps(Document pdfDocument, iTextSharp.text.Rectangle pdfPageSize, List <Bitmap> bitMaps) { int pageCount = bitMaps.Count; for (int i = 0; i < pageCount; i++) { System.Drawing.Image bitImg = (System.Drawing.Image)bitMaps[i]; iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitImg, BaseColor.WHITE); if (img.ScaledWidth > pdfPageSize.Width || img.ScaledHeight > pdfPageSize.Height) { if (img.DpiX != 0 && img.DpiY != 0 && img.DpiX != img.DpiY) { img.ScalePercent(100f); 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 ExportInvoiceToPdf() { Bitmap b = new Bitmap(Width, Height); DrawToBitmap(b, new Rectangle(0, 0, b.Width, b.Height)); Bitmap image = b; Document doc = new Document(PageSize.A4); PdfWriter.GetInstance(doc, new FileStream(Settings.Default.InvoiceSaveLocation + @"\" + labelSalesReceiptNumber.Text + ".pdf", FileMode.Create)); doc.Open(); iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, ImageFormat.Bmp); if (pdfImage.Height > pdfImage.Width) { //Maximum height is 800 pixels. float percentage = 0.0f; percentage = 700 / pdfImage.Height; pdfImage.ScalePercent(percentage * 100); } else { //Maximum width is 600 pixels. float percentage = 0.0f; percentage = 540 / pdfImage.Width; pdfImage.ScalePercent(percentage * 100); } doc.Add(pdfImage); doc.Close(); }
/// <summary> /// Add Image to Pdf from Image path. /// </summary> /// <param name="ImagePath">A Path</param> /// <param name="MaxHeight">Max Height Allowed</param> /// <param name="MaxWidth">Max Width Allowed</param> /// <exception cref="System.ArgumentNullException">ImagePath is null.</exception> /// <exception cref="System.UriFormatException">ImagePath is empty.-or- The scheme specified in ImagePath is not correctly formed.</exception> private static void AddImageWithWidthHeight(String ImagePath, Int32 MaxHeight = 700, Int32 MaxWidth = 600) { System.Drawing.Image Image = System.Drawing.Bitmap.FromFile(ImagePath); iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(Image, System.Drawing.Imaging.ImageFormat.Jpeg); if (pic.Height > pic.Width) { //Maximum height is 800 pixels. float percentage = 0.0f; percentage = MaxHeight / pic.Height; pic.ScalePercent(percentage * 100); } else { //Maximum width is 600 pixels. float percentage = 0.0f; percentage = 600 / pic.Width; pic.ScalePercent(percentage * 100); } pic.Border = iTextSharp.text.Rectangle.BOX; pic.BorderColor = iTextSharp.text.BaseColor.GREEN; pic.BorderWidth = 3f; ElementList.Add(pic); }
private iTextSharp.text.Image GetFlugzeugImage() { SqlConnection conn = new SqlConnection(DBconnStrg); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; //Get flugzeug pic cmd.CommandText = "SELECT f.flz_bild FROM termin_auftrag ta LEFT JOIN termin t ON (ta.ter_id = t.ter_id) LEFT JOIN termin_flugzeug tf ON (tf.ter_id = t.ter_id)" + " LEFT JOIN flugzeug f ON (f.flz_id = tf.flz_id)" + " WHERE ta.auf_id = " + FAuftragsID.ToString(); cmd.CommandType = System.Data.CommandType.Text; conn.Open(); SqlDataReader ResultSet = cmd.ExecuteReader(); BitmapImage BitObj = new BitmapImage(); byte[] a = null; if (ResultSet.Read()) { a = (byte[])ResultSet["flz_bild"]; } conn.Close(); if (a == null) { return(null); } iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(a); if (pic.Height > pic.Width) { //Maximum height is 50 pixels. float percentage = 0.0f; percentage = 50 / pic.Height; pic.ScalePercent(percentage * 100); } else { //Maximum width is 50 pixels. float percentage = 0.0f; percentage = 50 / pic.Width; pic.ScalePercent(percentage * 100); } pic.Border = iTextSharp.text.Rectangle.BOX; pic.BorderColor = iTextSharp.text.BaseColor.BLACK; pic.BorderWidth = 1f; return(pic); }
public string MontarPdfComImagens(List <string> listaDeImagens, string nomeArquivoPdf) { Log.Application.DebugFormat("Iniciando montagem de PDF com {0} paginas.", listaDeImagens.Count); var document = new Document(PageSize.A4, 0, 0, 0, 0); var imgAtual = string.Empty; try { PdfWriter.GetInstance(document, new FileStream(nomeArquivoPdf, FileMode.Create)); document.Open(); foreach (var image in listaDeImagens) { imgAtual = image; iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image); if (pic.Height > pic.Width) { float percentage = 0.0f; percentage = PageSize.A4.Height / pic.Height; pic.ScalePercent(percentage * 100); } else { float percentage = 0.0f; percentage = PageSize.A4.Width / pic.Width; pic.ScalePercent(percentage * 100); } document.Add(pic); document.NewPage(); } } catch (DocumentException exception) { Log.Application.Error(string.Format("Erro ao executar ItextSharp (Document Exception), na imagem {0}: ", imgAtual), exception); nomeArquivoPdf = string.Empty; } catch (IOException ioe) { Log.Application.Error(string.Format("Erro ao executar ItextSharp (IO), na imagem {0}: ", imgAtual), ioe); nomeArquivoPdf = string.Empty; } document.Close(); return(nomeArquivoPdf); }
private void pdf_button_Click(object sender, EventArgs e) { Document doc = new Document(iTextSharp.text.PageSize.LETTER, 20, 20, 42, 35); PdfWriter write = PdfWriter.GetInstance(doc, new FileStream("c:\\Codigos generados\\test.pdf", FileMode.Create)); doc.Open(); iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("logo.png"); PNG.ScalePercent(25f); doc.Add(PNG); Paragraph paragraph = new Paragraph(10, "Lista de usuarios registrados en el sistema"); doc.Add(paragraph); PdfPTable table = new PdfPTable(dataGridView_Clientes.Columns.Count); for (int j = 0; j < dataGridView_Clientes.Columns.Count; j++) { table.AddCell(new Phrase(dataGridView_Clientes.Columns[j].HeaderText)); } table.HeaderRows = 1; for (int i = 0; i < dataGridView_Clientes.Rows.Count; i++) { for (int k = 0; k < dataGridView_Clientes.Columns.Count; k++) { if (dataGridView_Clientes[k, i].Value != null) { table.AddCell(new Phrase(dataGridView_Clientes[k, i].Value.ToString())); } } } doc.Add(table); doc.Close(); System.Diagnostics.Process.Start("c:\\Codigos generados\\test.pdf"); }
public ActionResult GetImagePdf(string ID) { it.Font font = new it.Font(BaseFont.CreateFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10); MemoryStream ms = new MemoryStream(); it.Document document = new it.Document(); PdfWriter.GetInstance(document, ms); document.Open(); document.Add(new it.Paragraph("Yes Master!")); document.Add(new it.Paragraph("其疾如风,其徐如林,侵掠如火,不动如山,难知如阴,动如雷震", font)); List <string> imageStringList = GetImageString(ID, 1); foreach (var item in imageStringList) { try { //如果传过来的是Base64 //it.Image image = it.Image.GetInstance(base64ToPic(item), System.Drawing.Imaging.ImageFormat.Jpeg); //如果传过来的是地址 it.Image image = it.Image.GetInstance(Server.MapPath("~") + "/pdfimage/" + item + ".jpg"); image.Alignment = it.Image.ALIGN_LEFT; image.ScalePercent(30); document.Add(image); } catch (Exception e) { document.Add(new it.Paragraph("图片" + item + "不存在")); } } document.Close(); document.Dispose(); return(File(ms.ToArray(), "application/pdf", "ceshi.pdf")); }
private void button3_Click(object sender, EventArgs e) { using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF File|*.pdf", ValidateNames = true }) { if (sfd.ShowDialog() == DialogResult.OK) { iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER, 10, 10, 42, 35); try { PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create)); doc.Open(); iTextSharp.text.Image JPG = iTextSharp.text.Image.GetInstance("12046919_1726331607595049_7849083510719349652_n.jpg"); JPG.SetAbsolutePosition((PageSize.LETTER.Width - JPG.ScaledWidth), (JPG.ScaledHeight)); JPG.ScalePercent(30f); //JPG.SetAbsolutePosition(0, doc.PageSize.Height - JPG.ScaledHeight); doc.Add(JPG); rtRecibo.SelectAll(); rtRecibo.SelectionHangingIndent = 20; doc.Add(new iTextSharp.text.Paragraph(rtRecibo.Text.PadLeft(20))); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { doc.Close(); } } } }
//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 pdfdeneme_Load(object sender, EventArgs e) { iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfWriter.GetInstance(document, new FileStream(@"C:\deneme.pdf", FileMode.Create)); BaseFont arial = BaseFont.CreateFont("C:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(arial, 12, iTextSharp.text.Font.NORMAL); if (document.IsOpen() == false) { document.Open(); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@"C:\info.png"); img.ScalePercent(40f); document.Add(img); string text = "Kisi Ad : Adem \n" + "Kisi Soyad : Kesim \n" + "Kisi Ünvan : Yazılımcı"; text = TurkceKarakter(text); document.Add(new Paragraph(text, font)); document.Add(img); document.Close(); } }
public void ImageDirect(string savename, List <clsFileNanme_info> FilelistResult) { string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.jpg"; //临时文件路径 string fileName = string.Empty; { fileName = savename; Document document = new Document(); iTextSharp.text.Rectangle page = PageSize.A4; float y = page.Height; document = new Document(page, 15, 15, 30, 30); float docWidth = page.Width - 15 * 2; float docHeight = page.Height - document.BottomMargin - document.TopMargin; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); document.Open(); foreach (clsFileNanme_info item in FilelistResult) { iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(item.Filpath); float widthSzie = (page.Width - 30) / img1.Width; if (widthSzie < 1) { img1.ScalePercent(widthSzie * 100); } document.Add(img1); } document.Close(); } }
/// <summary> /// 导出PDF /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void simpleButtonExportPdf_Click(object sender, EventArgs e) { try { SaveFileDialog file = new SaveFileDialog(); file.InitialDirectory = "D:\\"; file.Filter = "Pdf Files(*.pdf)|*.pdf"; file.FileName = m_Model.ModelName.Split(' ')[0];//Modify by wwj 2013-01-18 指定导出PDF的文件名 if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) { WaitDialogForm m_WaitDialog = new WaitDialogForm("正在导出PDF文件...", "请稍后"); List <Bitmap> images = CurrentForm.zyEditorControl1.EMRDoc.GeneratePrintImage(); AddWaterMark(images);//Add by wwj 2013-01-18 图片上增加水印 Document doc = new Document(); PdfWriter.GetInstance(doc, new FileStream(file.FileName, FileMode.OpenOrCreate)); doc.Open(); foreach (Bitmap img in images) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance((System.Drawing.Image)img, BaseColor.WHITE); image.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN; image.ScalePercent(70); doc.Add(image); } doc.Close(); m_WaitDialog.Close(); m_WaitDialog.Dispose(); MessageBox.Show("导出成功!"); } } catch (Exception ex) { MyMessageBox.Show(1, ex); } }
public static void AdicionaImagem(string caminho, string imagem) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(caminho + imagem + ".jpg"); image.ScalePercent(25f); image.Alignment = Element.ALIGN_CENTER; document.Add(image); }
public ConfigureReportItextSharp(Font fonte_, iTextSharp.text.Image logo) { fonte = fonte_; logo.Alignment = 0; logo.ScalePercent(4); this.logotipo = logo; }
/// <summary> /// 图片转换PDF jpg,jpeg,png,tif,tiff /// </summary> /// <param name="imgfile">图片名称,包含路径</param> /// <param name="newPdfFile">pdf文件路径</param> /// <returns>返回转换成功后的PDF文件名称</returns> public static bool ImageConvertPdf(string imgfile, string newPdfFile, out string errorMsg) { try { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imgfile); float percentage = 1; float resizedWidht = image.Width; float resizedHeight = image.Height; while (resizedWidht > (image.Width - 36 - 36) * 0.8) { percentage = percentage * 0.9f; resizedHeight = image.Height * percentage; resizedWidht = image.Width * percentage; } while (resizedHeight > (image.Height - 36 - 36) * 0.8) { percentage = percentage * 0.9f; resizedHeight = image.Height * percentage; resizedWidht = image.Width * percentage; } image.ScalePercent(percentage * 100); iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(resizedWidht, resizedHeight); using (iTextSharp.text.Document doc = new iTextSharp.text.Document(rec)) { PdfWriter write = PdfWriter.GetInstance(doc, new FileStream(newPdfFile, FileMode.Create)); doc.Open(); doc.Add(image); } errorMsg = string.Empty; return(true); } catch (Exception ex) { errorMsg = ex.Message; return(false); } }
//print pdf for sales public void nsalesPdf() { Document doc = new Document(iTextSharp.text.PageSize.LETTER, 0, 0, 0, 0); PdfWriter PW = PdfWriter.GetInstance(doc, new FileStream("C:\\PMS\\Reports\\Sales pdf", FileMode.Create)); doc.Open();//open document to write iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("C:\\PMS\\Resources\\faith2.png"); img.ScalePercent(79f); // img.SetAbsolutePosition(doc.PageSize.Width - 250f - 250f, doc.PageSize.Height - 30f - 20.6f); doc.Add(img); //add image to document Paragraph p = new Paragraph(" Sales Report"); doc.Add(p); DateTime time = DateTime.Now; Paragraph p2 = new Paragraph(" " + this.rowCountLabel.Text + " Produced On " + time.ToString() + " \n\n"); doc.Add(p2); //load data from datagrid PdfPTable table = new PdfPTable(viewSalesdataGridView.Columns.Count); //add headers from the datagridview to the table for (int j = 0; j < viewSalesdataGridView.Columns.Count; j++) { table.AddCell(new Phrase(viewSalesdataGridView.Columns[j].HeaderText)); } //flag the first row as header table.HeaderRows = 1; //add the actual rows to the table from datagridview for (int i = 0; i < viewSalesdataGridView.Rows.Count; i++) { for (int k = 0; k < viewSalesdataGridView.Columns.Count; k++) { if (viewSalesdataGridView[k, i].Value != null) { table.AddCell(new Phrase(viewSalesdataGridView[k, i].Value.ToString())); } } } doc.Add(table); //end querying from datagrid doc.Close();//close document after writting in MessageBox.Show("Sales Report generated Successful"); System.Diagnostics.Process.Start("C:\\PMS\\Reports\\Sales pdf"); }
private void LoadPrint() { try { SaveFileDialog file = new SaveFileDialog(); file.InitialDirectory = "D:\\"; file.Filter = "Pdf Files(*.pdf)|*.pdf"; file.FileName = "病案首页"; if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) { WaitDialogForm m_WaitDialog = new WaitDialogForm("正在导出PDF文件...", "请稍后"); Document doc = new Document(); PdfWriter.GetInstance(doc, new FileStream(file.FileName, FileMode.OpenOrCreate)); doc.Open(); List <Bitmap> bitmapList = util.GetPrintImage(); foreach (var item in bitmapList) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(item, BaseColor.WHITE); image.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN; image.ScalePercent(70); doc.Add(image); } doc.Close(); m_WaitDialog.Close(); m_WaitDialog.Dispose(); YiDanMessageBox.Show("导出成功!"); } } catch (Exception ex) { YiDanMessageBox.Show(ex.Message); } }
private static void WriteTempPDF(ArrayList docTypeArray) { Document doc = new Document(PageSize.LETTER); try { PdfWriter.GetInstance(doc, new FileStream(Properties.Settings.Default.TempDirectory + @"\Temp.pdf", FileMode.Create)); doc.Open(); //Bitmap OBSelfConfigBarcode = CreateBarcode("OBSELFCONFIG"); //iTextSharp.text.Image OBSFBBitmap = iTextSharp.text.Image.GetInstance(OBSelfConfigBarcode, System.Drawing.Imaging.ImageFormat.Bmp); //OBSFBBitmap.ScalePercent(8f); //OBSFBBitmap.SetAbsolutePosition(25.74f, 779.985f - OBSFBBitmap.ScaledHeight); Bitmap thisSideUpLabel = CreateLabel("^^ This End Up ^^"); iTextSharp.text.Image upLabel = iTextSharp.text.Image.GetInstance(thisSideUpLabel, System.Drawing.Imaging.ImageFormat.Bmp); upLabel.ScalePercent(8f); upLabel.SetAbsolutePosition(((doc.PageSize.Width / 2f) - (upLabel.ScaledWidth / 2f)), doc.PageSize.Height - 60f); for (Int32 x = 0; x < docTypeArray.Count; x++) { //doc.Add(OBSFBBitmap); doc.Add(upLabel); Bitmap barCode = CreateBarcode(((CheckedListBoxItem)docTypeArray[x]).ItemValue.ToString()); iTextSharp.text.Image bitmap = iTextSharp.text.Image.GetInstance(barCode, System.Drawing.Imaging.ImageFormat.Bmp); bitmap.ScalePercent(20f); //bitmap.SetAbsolutePosition(doc.PageSize.Width - bitmap.ScaledWidth - 30f, doc.PageSize.Height - bitmap.ScaledHeight - 30f); bitmap.SetAbsolutePosition(((doc.PageSize.Width / 2f) - (bitmap.ScaledWidth / 2f)), doc.PageSize.Height - bitmap.ScaledHeight - 200f); doc.Add(bitmap); Bitmap docTypeLabel = CreateLabel(((CheckedListBoxItem)docTypeArray[x]).DisplayName.ToString()); iTextSharp.text.Image docLabel = iTextSharp.text.Image.GetInstance(docTypeLabel, System.Drawing.Imaging.ImageFormat.Bmp); docLabel.ScalePercent(20f); docLabel.SetAbsolutePosition(((doc.PageSize.Width / 2f) - (docLabel.ScaledWidth / 2f)), ((doc.PageSize.Height / 2f) - (docLabel.ScaledHeight / 2f))); doc.Add(docLabel); if (x != (docTypeArray.Count - 1)) { doc.NewPage(); } } } catch (DocumentException dex) { Console.Write(dex.Message); } catch (IOException ioex) { Console.Write(ioex.Message); } catch (Exception ex) { Console.Write(ex.Message); } finally { doc.Close(); } }
public override void OnEndPage(PdfWriter writer, Document doc) { BaseColor grey = new BaseColor(128, 128, 128); Font font = FontFactory.GetFont("Arial", 9, Font.NORMAL, grey); //tbl footer PdfPTable footerTbl = new PdfPTable(1); footerTbl.TotalWidth = doc.PageSize.Width; //img footer iTextSharp.text.Image foot = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("footer.jpg")); foot.ScalePercent(45); footerTbl.HorizontalAlignment = Element.ALIGN_CENTER; PdfPCell cell = new PdfPCell(foot); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.Border = 0; footerTbl.AddCell(cell); //page number Chunk myFooter = new Chunk("Page " + (doc.PageNumber), FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 8, grey)); PdfPCell footer = new PdfPCell(new Phrase(myFooter)); footer.Border = Rectangle.NO_BORDER; footer.HorizontalAlignment = Element.ALIGN_CENTER; footerTbl.AddCell(footer); //this is for the position of the footer ... im my case is "+80" footerTbl.WriteSelectedRows(0, -1, 0, (doc.BottomMargin + 80), writer.DirectContent); }
private static void WritePDF(String data, Bitmap barCode) { Document doc = new Document(PageSize.LETTER); try { PdfWriter.GetInstance(doc, new FileStream(@"C:\Test.pdf", FileMode.Create)); doc.Open(); iTextSharp.text.Image bitmap = iTextSharp.text.Image.GetInstance(barCode, System.Drawing.Imaging.ImageFormat.Bmp); bitmap.ScalePercent(24f); bitmap.SetAbsolutePosition(((doc.PageSize.Width / 2f) - (bitmap.ScaledWidth / 2f)), ((doc.PageSize.Height / 2f) - (bitmap.ScaledHeight / 2f))); doc.Add(bitmap); doc.NewPage(); doc.Add(bitmap); } catch (DocumentException dex) { Console.Write(dex.Message); } catch (IOException ioex) { Console.Write(ioex.Message); } catch (Exception ex) { Console.Write(ex.Message); } finally { doc.Close(); } }
private void Print_btn_click(object sender, EventArgs e) { FileStream fs = new FileStream("Ticket.pdf", FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Rectangle rec2 = new iTextSharp.text.Rectangle(PageSize.A4); rec2.BackgroundColor = new BaseColor(Color.LightBlue); Document doc = new Document(rec2); PdfWriter wri = PdfWriter.GetInstance(doc, fs); doc.Open(); iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("logo.png"); PNG.ScalePercent(40f); PNG.SetAbsolutePosition(doc.PageSize.Width - 46f - 75f, doc.PageSize.Height - 36f - 105f); Paragraph par = new Paragraph(" Railway Enquiry System "); Paragraph par1 = new Paragraph(" Ticket ID : " + Ticketidtbox.Text + "\nTrain Name : " + TrainNametbox.Text + "\nFrom : " + Fromtbox.Text + " To : " + totbox.Text + "\nJourney Date : " + JourneydateTP.Text + " Starting Time : " + Stimetbox.Text); Paragraph par2 = new Paragraph("Passenger Name : " + pnametbox.Text + " Reaching Time : " + RTimetbox.Text + "\nGender : " + pgendertbox.Text + "\nNumber of Seat : " + Seatstbox.Text + " Seat Type : " + snametbox.Text + "\nGender : " + pgendertbox.Text + "\nPrice : " + pricetbox.Text); doc.Add(PNG); doc.Add(par); doc.Add(par1); doc.Add(par2); doc.Close(); MessageBox.Show("Successfully Ticket Printed", "Print Info"); this.Printbtn.Enabled = false; }
public int AddImage(string imagePath, string titre = null, string stampString = null, string fileNotFoundMessage = null) { AssertGoodInitialization(); if (!File.Exists(imagePath)) { CreateMissingFilePage("Photo introuvable", imagePath, fileNotFoundMessage); } else { AddNewContentPage(); CreateStamp(stampString); WriteText("\n", null, null, null, false); WriteTitle(titre, 1, true, true, false, true); iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(imagePath); var docHeight = PageSize.A4.Height - _docContent.BottomMargin - _docContent.TopMargin - 150; var docWidth = PageSize.A4.Width - _docContent.LeftMargin - _docContent.RightMargin - 150; if (pic.Width > docWidth || pic.Height > docHeight) { var scalePercent = docWidth / pic.Width * 100; scalePercent = Math.Min(scalePercent, docHeight / pic.Height * 100); pic.ScalePercent(scalePercent); } // centrage de l'image pic.SetAbsolutePosition((PageSize.A4.Width - pic.ScaledWidth) / 2, (PageSize.A4.Height - pic.ScaledHeight) / 2); pic.Border = iTextSharp.text.Rectangle.BOX; pic.BorderColor = iTextSharp.text.BaseColor.BLACK; pic.BorderWidth = 1f; _docContent.Add(pic); } return(1); }
private void button11_Click(object sender, EventArgs e) { string ID = label16.Text; string sum = label12.Text; dataGridView3.DataSource = FillTable("select * from sold_products where customer_id=" + ID); label16.Text = GetID("select * from customer", "customer_id").ToString(); Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("Item list " + ID + ".pdf", FileMode.Create)); doc.Open(); iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance("pic.jpg"); png.ScalePercent(25f); png.BorderColor = iTextSharp.text.BaseColor.BLACK; png.SetAbsolutePosition(doc.PageSize.Width - 200f - 200f, doc.PageSize.Height - 80f - 30f); doc.Add(png); List list = new List(List.UNORDERED, 10f); Paragraph para = new Paragraph("\n\n"); doc.Add(para); list.Add("User: "******""); list.Add("Date Time: " + dateTime + ""); list.Add("ID Number: " + ID + ""); list.Add("Customer Name: Respected Customer\n\n\n"); doc.Add(list); PdfPTable table = new PdfPTable(dataGridView3.Columns.Count); for (int i = 0; i < dataGridView3.Columns.Count; i++) { table.AddCell(new Phrase(dataGridView3.Columns[i].HeaderText)); } table.HeaderRows = 1; for (int i = 0; i < dataGridView3.Rows.Count; i++) { for (int j = 0; j < dataGridView3.Columns.Count; j++) { if (dataGridView3[j, i].Value != null) { table.AddCell(new Phrase(dataGridView3[j, i].Value.ToString())); } } } doc.Add(table); Paragraph para0 = new Paragraph("\n\n"); doc.Add(para0); List list1 = new List(List.UNORDERED, 10f); Paragraph para1 = new Paragraph("\n\n"); list1.Add("Total number of item(s) = " + label3.Text + ""); list1.Add("Total price = " + sum + ""); doc.Add(list1); para1.IndentationLeft = 40f; para1.Add("Thank you! :)"); doc.Add(para1); doc.Close(); System.Diagnostics.Process.Start("Item list " + ID + ".pdf"); MessageBox.Show("Pdf Created Successfully!"); }
private static void SetTitle(Document doc) { // Set Logo System.Drawing.Image bitmap = Resources.ImagesResources.Logo_Inverso_black; iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(bitmap, BaseColor.WHITE); image.ScalePercent(26f); image.Alignment = Element.ALIGN_RIGHT; doc.Add(image); // Set Title PdfPCell cell = new PdfPCell(new Phrase(Properties.Resources.Title, fontTitle)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, BackgroundColor = darkBlue, FixedHeight = 30f, BorderWidth = (float)0, Padding = (float)5, }; var table = new PdfPTable(1); table.WidthPercentage = 100; table.AddCell(cell); doc.Add(table); // Empty rows after title doc.Add(new Paragraph(" ")); }
private void imprimir_button_Click(object sender, EventArgs e) { string fecha = string.Format("{0:yyyy-MM-dd HH-mm-ss-fff}", Convert.ToDateTime(DateTime.Now)); if (impresion) { new DAOImpresion().ImprimirTicketCorte(usuarioActual, usuarios_combobox.Text, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), total_label.Text, listaDeCortes); //Realizo PDF Document doc = new Document(iTextSharp.text.PageSize.LETTER, 20, 20, 42, 35); string pathString2 = @"c:\PDF Generados"; //Verifico si exite la carpeta PDF Generados if (!System.IO.File.Exists(pathString2)) { System.IO.Directory.CreateDirectory(pathString2); PdfWriter write = PdfWriter.GetInstance(doc, new FileStream("c:\\PDF Generados\\CorteVenta " + fecha + ".pdf", FileMode.Create)); } else { PdfWriter write = PdfWriter.GetInstance(doc, new FileStream("c:\\PDF Generados\\CorteVenta " + fecha + ".pdf", FileMode.Create)); } doc.Open(); string rutaimg = Path.Combine(Application.StartupPath, "Resources\\logo.png"); iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance(rutaimg); PNG.ScalePercent(25f); doc.Add(PNG); Paragraph paragraph = new Paragraph(10, "Corte de ventas realizado por el usuario: " + usuarioActual.Nombre); doc.Add(paragraph); Paragraph paragraph2 = new Paragraph(11, "Total: $" + totalTodo); doc.Add(paragraph2); PdfPTable table = new PdfPTable(dataGridView1.Columns.Count); for (int j = 0; j < dataGridView1.Columns.Count; j++) { table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText)); } table.HeaderRows = 1; for (int i = 0; i < dataGridView1.Rows.Count; i++) { for (int k = 0; k < dataGridView1.Columns.Count; k++) { if (dataGridView1[k, i].Value != null) { table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString())); } } } doc.Add(table); doc.Close(); System.Diagnostics.Process.Start("c:\\PDF Generados\\CorteVenta " + fecha + ".pdf"); new DAOCorreo().CrearCorreoYMandar("c:\\PDF Generados\\CorteVenta " + fecha + ".pdf", usuarioActual); impresion = false; } else { MessageBox.Show("Debe de seleccionar un usuario.", "Cortes", MessageBoxButtons.OK, MessageBoxIcon.Question); impresion = false; } }
private void button1_Click(object sender, EventArgs e) { using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF File|*.pdf", ValidateNames = true }) { if (sfd.ShowDialog() == DialogResult.OK) { iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 140f, 10f); try { PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create)); doc.Open(); iTextSharp.text.Image JPG = iTextSharp.text.Image.GetInstance("12046919_1726331607595049_7849083510719349652_n.jpg"); JPG.SetAbsolutePosition((PageSize.LETTER.Width - JPG.ScaledWidth) / 2, (PageSize.LETTER.Height - JPG.ScaledHeight) / 2); JPG.ScalePercent(30f); //JPG.SetAbsolutePosition(0, doc.PageSize.Height - JPG.ScaledHeight); doc.Add(JPG); richTextBox1.SelectAll(); richTextBox1.SelectionHangingIndent = 20; doc.Add(new iTextSharp.text.Paragraph(richTextBox1.Text.PadLeft(20))); PdfPTable table = new PdfPTable(dataGridView1.Columns.Count); for (int j = 0; j < dataGridView1.Columns.Count; j++) { table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText)); } table.HeaderRows = 1; for (int i = 0; i < dataGridView1.Rows.Count; i++) { for (int k = 0; k < dataGridView1.Columns.Count; k++) { if (dataGridView1[k, i].Value != null) { table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString())); } } } doc.Add(table); doc.Add(new iTextSharp.text.Paragraph(textBox1.Text.PadLeft(20))); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { doc.Close(); } } } }
/// <summary> /// Insert Image at specified Position (X , Y) /// </summary> /// <param name="doc">Pdf Document</param> /// <param name="fitwidth">Width</param> /// <param name="fitheight">Height</param> /// <param name="Percent">Image Percent</param> /// <param name="absoluteX">X : Position</param> /// <param name="absoluteY">Y : Position</param> /// <param name="InstanceImage">Image Directory</param> public void InsertImage(Document doc, float fitwidth, float fitheight, float Percent, float absoluteX, float absoluteY, string InstanceImage) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(InstanceImage); image.ScaleToFit(fitwidth, fitheight); image.ScalePercent(Percent); image.SetAbsolutePosition(absoluteX, absoluteY); doc.Add(image); }
private void Button5_Click(object sender, EventArgs e) { if (dataGridView.RowCount == 0) { MessageBox.Show("No Hay Datos Para Realizar Un Reporte"); } else { //ESCOJE A RUTA DONDE GUARDAREMOS EL PDF SaveFileDialog save = new SaveFileDialog(); save.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*"; if (save.ShowDialog() == DialogResult.OK) { filename = save.FileName; //definimos la hoja y los margenes Document doc = new Document(PageSize.LETTER.Rotate(), 10f, 10f, 10f, 10f); try { //LA FUENTE DE NUESTRO TEXTO iTextSharp.text.Font fuente = FontFactory.GetFont("Times New Roman", 10, new iTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#000"))); DateTime thisDay = DateTime.Today; Paragraph para = new Paragraph(thisDay.ToString("D"), fuente); FileStream file = new FileStream(filename, FileMode.Create); PdfWriter writer = PdfWriter.GetInstance(doc, file); writer.ViewerPreferences = PdfWriter.PageModeUseThumbs; writer.ViewerPreferences = PdfWriter.PageLayoutOneColumn; doc.Open(); // Creamos la imagen y le ajustamos el tamaño iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(Application.StartupPath + "/refriauto.png"); imagen.BorderWidth = 0; imagen.Alignment = Element.ALIGN_LEFT; float percentage = 0.0f; percentage = 150 / imagen.Width; imagen.ScalePercent(percentage * 90); // Insertamos la imagen en el documento doc.Add(imagen); // Insertamos la fecha para.Alignment = Element.ALIGN_RIGHT; doc.Add(para); doc.Add(new Paragraph(" ")); //metodo para generar el reporte GenerarDocumentos(doc); Process.Start(filename); doc.Close(); writer.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
private void Add_Footer_Logo(Document doc) { string fontpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/dist/img/"); iTextSharp.text.Image imagen = Image.GetInstance(fontpath + "footer_template.jpg"); imagen.ScalePercent(62f); imagen.SetAbsolutePosition(0, 0); doc.Add(imagen); }
/// <summary> /// This method create the image on the base of the byte array /// </summary> /// <param name="data"></param> /// <returns></returns> public iTextSharp.text.Image GetImage(byte[] data) { image = iTextSharp.text.Image.GetInstance(byteArrayToImage1(data), System.Drawing.Imaging.ImageFormat.Jpeg); image.ScalePercent(200); return image; }
private Image ScaleImage(Image image) { image.ScalePercent(ScalePercent); return image; }