private static PDFFlowContent BuildHeader(PDFAnsiTrueTypeFont verdana, PDFImage logoImage) { PDFFlowTableContent headerTable = new PDFFlowTableContent(2); PDFFlowTableRow row = headerTable.Rows.AddRowWithCells("Invoice", logoImage); PDFAnsiTrueTypeFont headerFont = new PDFAnsiTrueTypeFont(verdana); headerFont.Size = 36; (row.Cells[0] as PDFFlowTableStringCell).Font = headerFont; row.Cells[0].VerticalAlign = PDFGraphicAlign.Center; row.Cells[1].HorizontalAlign = PDFGraphicAlign.Far; (row.Cells[1] as PDFFlowTableImageCell).ImageWidth = 135; return(headerTable); }
private void WriteImage(Path visual, ImageBrush brush) { System.Windows.Media.Imaging.BitmapFrame frame = brush.ImageSource as System.Windows.Media.Imaging.BitmapFrame; PDFImage img = PDFDocument.CreateObject <PDFImage>(); string key = "R" + Page.Resources.ID + "I" + img.ID; Page.Resources.XObject[key] = img; img.ColorSpace = "DeviceRGB"; img.BitsPerComponent = 8; System.Windows.Media.Imaging.JpegBitmapEncoder enc = new JpegBitmapEncoder(); /*TransformedBitmap tb = new TransformedBitmap(frame, new ScaleTransform { * ScaleX = brush.Viewport.Width / frame.Width , * ScaleY = brush.Viewport.Height / frame.Height * });*/ var tb = frame; img.Width = tb.PixelWidth; img.Height = tb.PixelHeight; enc.Frames.Add(BitmapFrame.Create(tb)); enc.QualityLevel = 100; enc.Save(img.Stream); Page.ContentStream.WriteLine("q"); PathGeometry pg = PathGeometry.CreateFromGeometry(visual.Data); Point p = pg.Figures.First().StartPoint; p = TransformPoint(visual, p); Page.ContentStream.WriteLine("{0} 0 0 {1} {2} {3} cm", brush.Viewport.Width, brush.Viewport.Height, p.X, p.Y - brush.Viewport.Height); Page.ContentStream.WriteLine("/" + key + " Do"); Page.ContentStream.WriteLine("Q"); }
private void CopyIndexedMemoryBitmap(int bits /*, ref bool hasAlpha*/, ImageDataBitmap dest) { int firstMaskColor = -1, lastMaskColor = -1; bool segmentedColorMask = false; int bytesColorPaletteOffset = ((ImagePrivateDataBitmap)Image.Data).ColorPaletteOffset; // GDI+ always returns Windows bitmaps: sizeof BITMAPFILEHEADER + sizeof BITMAPINFOHEADER int bytesFileOffset = ((ImagePrivateDataBitmap)Image.Data).Offset; uint paletteColors = Image.Information.ColorsUsed; int width = (int)Image.Information.Width; int height = (int)Image.Information.Height; MonochromeMask mask = new MonochromeMask(width, height); bool isGray = bits == 8 && (paletteColors == 256 || paletteColors == 0); int isBitonal = 0; // 0: false; >0: true; <0: true (inverted) byte[] paletteData = new byte[3 * paletteColors]; for (int color = 0; color < paletteColors; ++color) { paletteData[3 * color] = Data[bytesColorPaletteOffset + 4 * color + 2]; paletteData[3 * color + 1] = Data[bytesColorPaletteOffset + 4 * color + 1]; paletteData[3 * color + 2] = Data[bytesColorPaletteOffset + 4 * color + 0]; if (isGray) { isGray = paletteData[3 * color] == paletteData[3 * color + 1] && paletteData[3 * color] == paletteData[3 * color + 2]; } if (Data[bytesColorPaletteOffset + 4 * color + 3] < 128) { // We treat this as transparency: if (firstMaskColor == -1) { firstMaskColor = color; } if (lastMaskColor == -1 || lastMaskColor == color - 1) { lastMaskColor = color; } if (lastMaskColor != color) { segmentedColorMask = true; } } //else //{ // // We treat this as opacity: //} } if (bits == 1) { if (paletteColors == 0) { isBitonal = 1; } if (paletteColors == 2) { if (paletteData[0] == 0 && paletteData[1] == 0 && paletteData[2] == 0 && paletteData[3] == 255 && paletteData[4] == 255 && paletteData[5] == 255) { isBitonal = 1; // Black on white } if (paletteData[5] == 0 && paletteData[4] == 0 && paletteData[3] == 0 && paletteData[2] == 255 && paletteData[1] == 255 && paletteData[0] == 255) { isBitonal = -1; // White on black } } } // NYI: (no sample found where this was required) // if (segmentedColorMask = true) // { ... } bool isFaxEncoding = false; byte[] imageData = new byte[(width * bits + 7) / 8 * height]; byte[] imageDataFax = null; int k = 0; if (bits == 1 && dest._document.Options.EnableCcittCompressionForBilevelImages) { // TODO: flag/option? // We try Group 3 1D and Group 4 (2D) encoding here and keep the smaller byte array. //byte[] temp = new byte[imageData.Length]; //int ccittSize = DoFaxEncoding(ref temp, imageBits, (uint)bytesFileOffset, (uint)width, (uint)height); // It seems that Group 3 2D encoding never beats both other encodings, therefore we don't call it here. //byte[] temp2D = new byte[imageData.Length]; //uint dpiY = (uint)image.VerticalResolution; //uint kTmp = 0; //int ccittSize2D = DoFaxEncoding2D((uint)bytesFileOffset, ref temp2D, imageBits, (uint)width, (uint)height, dpiY, out kTmp); //k = (int) kTmp; byte[] tempG4 = new byte[imageData.Length]; int ccittSizeG4 = PDFImage.DoFaxEncodingGroup4(ref tempG4, Data, (uint)bytesFileOffset, (uint)width, (uint)height); isFaxEncoding = /*ccittSize > 0 ||*/ ccittSizeG4 > 0; if (isFaxEncoding) { //if (ccittSize == 0) // ccittSize = 0x7fffffff; if (ccittSizeG4 == 0) { ccittSizeG4 = 0x7fffffff; } //if (ccittSize <= ccittSizeG4) //{ // Array.Resize(ref temp, ccittSize); // imageDataFax = temp; // k = 0; //} //else { Array.Resize(ref tempG4, ccittSizeG4); imageDataFax = tempG4; k = -1; } } } //if (!isFaxEncoding) { int bytesOffsetRead = 0; if (bits == 8 || bits == 4 || bits == 1) { int bytesPerLine = (width * bits + 7) / 8; for (int y = 0; y < height; ++y) { mask.StartLine(y); int bytesOffsetWrite = (height - 1 - y) * ((width * bits + 7) / 8); for (int x = 0; x < bytesPerLine; ++x) { if (isGray) { // Lookup the gray value from the palette: imageData[bytesOffsetWrite] = paletteData[3 * Data[bytesFileOffset + bytesOffsetRead]]; } else { // Store the palette index. imageData[bytesOffsetWrite] = Data[bytesFileOffset + bytesOffsetRead]; } if (firstMaskColor != -1) { int n = Data[bytesFileOffset + bytesOffsetRead]; if (bits == 8) { // TODO???: segmentedColorMask == true => bad mask NYI mask.AddPel(n >= firstMaskColor && n <= lastMaskColor); } else if (bits == 4) { // TODO???: segmentedColorMask == true => bad mask NYI int n1 = (n & 0xf0) / 16; int n2 = n & 0x0f; mask.AddPel(n1 >= firstMaskColor && n1 <= lastMaskColor); mask.AddPel(n2 >= firstMaskColor && n2 <= lastMaskColor); } else if (bits == 1) { // TODO???: segmentedColorMask == true => bad mask NYI for (int bit = 1; bit <= 8; ++bit) { int n1 = (n & 0x80) / 128; mask.AddPel(n1 >= firstMaskColor && n1 <= lastMaskColor); n *= 2; } } } bytesOffsetRead += 1; bytesOffsetWrite += 1; } bytesOffsetRead = 4 * ((bytesOffsetRead + 3) / 4); // Align to 32 bit boundary } } else { throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format #3"); } } dest.Data = imageData; dest.Length = imageData.Length; if (imageDataFax != null) { dest.DataFax = imageDataFax; dest.LengthFax = imageDataFax.Length; } dest.IsGray = isGray; dest.K = k; dest.IsBitonal = isBitonal; dest.PaletteData = paletteData; dest.PaletteDataLength = paletteData.Length; dest.SegmentedColorMask = segmentedColorMask; //if (alphaMask != null) //{ // dest.AlphaMask = alphaMask; // dest.AlphaMaskLength = alphaMask.Length; //} if (mask != null && firstMaskColor != -1) { dest.BitmapMask = mask.MaskData; dest.BitmapMaskLength = mask.MaskData.Length; } }
public static bool Tiff2PDFPageByPage(string _tiffFilePath, string _pdfFilePath) { try { // Create the pdf document PDFDocument doc = new PDFDocument(); //Serial number goes here doc.SerialNumber = "PDF4NET-AYBAM-8ARRR-B4EX2-OXGCC-KN2Q5"; // Load TIFF file Bitmap bitmap = new Bitmap(_tiffFilePath); // Calculate number of pages/images used in TIFF file FrameDimension frameDimension = new FrameDimension(bitmap.FrameDimensionsList[0]); int framesCount = bitmap.GetFrameCount(frameDimension); for (int i = 0; i < framesCount; i++) { // Create a new page PDFPage page = doc.AddPage(); // draw the current tiff frame on the page PDFImage image = new PDFImage(bitmap, i); page.Canvas.DrawImage(image, 0, 0, page.Width, page.Height, 0, PDFKeepAspectRatio.KeepNone); } doc.Save(_pdfFilePath); bitmap.Dispose(); return true; } catch { return false; } }
private void btnPrint_Click(object sender, EventArgs e) { try { ExportData exportdata = new ExportData(); byte[] pdfOutput = null; byte[] pdfInput = File.ReadAllBytes("Template.pdf"); using (var ms = new MemoryStream(pdfInput)) { using (var outputMs = new MemoryStream()) { var options = new PDFCreationOptions(); options.Viewer.ViewerPreferences = ViewerPreference.CenterWindow; var document = new PDFDocument(outputMs, options); document.Pages.Delete(document.CurrentPage); document.LoadPdf(ms, ""); document.Pages.Insert(1); #region Logo TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap)); Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(Convert.FromBase64String(_settings.LogoBase64)); PDFImage logo = new PDFImage(bitmap1); logo.Width = 100; logo.Height = 100; logo.KeepAspectRatio = true; document.CurrentPage.Body.AddImage(logo, -50, -20); #endregion #region Company Details document.CurrentPage.Body.SetTextAlignment(TextAlign.Left); document.CurrentPage.Body.SetActiveFont("Tahoma", PDFFontStyles.Regular, 8.25); document.CurrentPage.Body.AddTextArea(new RectangleF(-50, 50, 200, 200), _settings.CompanyDetails, true); #endregion #region Driver document.CurrentPage.Body.SetTextAlignment(TextAlign.Left); document.CurrentPage.Body.SetActiveFont("Tahoma", PDFFontStyles.Regular, 14.25); document.CurrentPage.Body.AddTextArea(new RectangleF(480, -40, 200, 200), "Statement #" + txtStatement.Text, true); document.CurrentPage.Body.AddTextArea(new RectangleF(450, -20, 200, 200), _settings.LastDriver.Name, true); document.CurrentPage.Body.AddTextArea(new RectangleF(490, 0, 200, 200), datCurrentDate.Value.ToString("MM/dd/yyyy"), true); document.CurrentPage.Body.AddTextArea(new RectangleF(430, 25, 200, 200), "Unit# " + cmbUnits.Text, true); document.CurrentPage.Body.SetTextAlignment(TextAlign.Left); document.CurrentPage.Body.SetActiveFont("Tahoma", PDFFontStyles.Bold, 10); document.CurrentPage.Body.AddTextArea(new RectangleF(-27, 150, 200, 200), _settings.LastDriver.Name, true); document.CurrentPage.Body.AddTextArea(new RectangleF(-27, 165, 200, 200), _settings.LastDriver.Address, true); #endregion double lastHeigth = 270; double totalGridWidth = 0; double totalTableEndX = 0; int totalRowsCount = 0; float totalCheckAmount = 0; int tabelIndex = 0; int currentPage = 0; int tableXStart = -60; double checkAmountWidth = 0; double checkAmountValueWidth = 0; for (int j = panelMain.Controls.Count - 1; j >= 0; j--) { var control = panelMain.Controls[j]; if (control is ucTable) { tabelIndex++; string header = (control as ucTable).GetHeader(); List <ColumnSettings> columns = (control as ucTable).GetColumns(); List <List <string> > rows = (control as ucTable).GetRowsValues(); ExportData.ExportTable exportTabel = new ExportData.ExportTable(); exportTabel.Rows = rows; exportdata.TableList.Add(exportTabel); if (rows == null || rows.Count == 0) { continue; } Table table = new Table(columns.Count); table.width = 700; table.DisplayHeader = true; table.style.borderBottomType = borderType.none; table.style.borderLeftType = borderType.none; table.style.borderRightType = borderType.none; table.headerStyle.borderType = borderType.solid; table.headerStyle.borderColor = Color.Black; table.headerStyle.borderWidth = 1; table.headerStyle.fontStyle = TableFontStyle.bold; table.headerStyle.fontSize = 8.5; table.headerStyle.fontName = "Tahoma"; table.headerStyle.backgroundColor = Color.LightGray; float totalTable = 0; for (int row = 0; row < rows.Count; row++) { if (string.IsNullOrEmpty(rows[row][columns.Count - 1])) { continue; } table.addRow(); for (int column = 0; column < columns.Count; column++) { Cell cell = table.cell(row, column); cell.style.borderType = borderType.solid; cell.style.fontName = "Tahoma"; cell.style.borderWidth = 1; cell.style.borderColor = Color.Black; if (row == 0) { table.column(column).width = table.width * (double)columns[column].Percentage / 100; table.column(column).header.SetValue(columns[column].Name); table.column(column).header.style.textAlign = TextAlignment.center; if (column == columns.Count - 2) { checkAmountWidth = table.column(column).width; } if (column == columns.Count - 1) { checkAmountValueWidth = table.column(column).width; } } if (columns[column].Name.Equals("Amount")) { var cel = table.cell(row, column); cel.style.fontStyle = TableFontStyle.bold; cel.style.fontName = "Tahoma"; totalTable += float.Parse(rows[row][column]); cel.SetValue("$" + float.Parse(rows[row][column]).ToString("N")); cel.style.textAlign = TextAlignment.center; cel.style.fontColor = Color.Black; cell.style.borderColor = Color.Black; } else { var cel = table.cell(row, column); cel.SetValue(rows[row][column]); cel.style.textAlign = TextAlignment.center; cel.style.fontName = "Tahoma"; cell.style.borderColor = Color.Black; } } } #region Add row for total table.addRow(); for (int column = 0; column < columns.Count; column++) { var cell = table.cell(table.rowCount - 1, column); cell.style.fontStyle = TableFontStyle.bold; cell.style.fontName = "Tahoma"; if (column == columns.Count - 2) { cell.SetValue("Total:"); cell.style.textAlign = TextAlignment.right; cell.style.borderType = borderType.solid; cell.style.borderType = borderType.solid; cell.style.borderWidth = 1; cell.style.borderColor = Color.Black; } else if (column == columns.Count - 1) { cell.SetValue("$" + totalTable.ToString("N")); cell.style.textAlign = TextAlignment.center; cell.style.borderType = borderType.solid; cell.style.borderWidth = 1; cell.style.borderColor = Color.Black; cell.style.fontColor = Color.DarkRed; cell.style.borderType = borderType.solid; } else { cell.style.borderType = borderType.none; // cell.style.borderBottomColor = Color.White; } } //table.addRow();//??? //for (int column = 0; column < columns.Count; column++) //{ // var cell = table.cell(table.rowCount - 1, column); // cell.style.borderType = borderType.none; //} #endregion #region Add Check Amount if ((control as ucTable).SeScade()) { totalCheckAmount -= totalTable; } else { totalCheckAmount += totalTable; } #endregion totalRowsCount += table.rowCount; if (totalRowsCount > 15 && currentPage == 0) { document.SetCurrentPage(1); currentPage = 1; lastHeigth = 0; } document.CurrentPage.Body.SetTextAlignment(TextAlign.Left); document.CurrentPage.Body.SetActiveFont("Tahoma", PDFFontStyles.Bold, 10); document.CurrentPage.Body.AddTextArea(new RectangleF(-60, (int)lastHeigth - 20, 700, 20), header, true); document.Pages[currentPage].Body.DrawTable(table, tableXStart, lastHeigth); lastHeigth += table.rowCount * 25 + 65; totalGridWidth = table.column(table.columnCount - 1).width + table.column(table.columnCount - 2).width; totalTableEndX = 0; for (int i = 0; i <= table.columnCount - 3; i++) { totalTableEndX += table.column(i).width; } } } //??? Table tableTOTAL = new Table(2); tableTOTAL.width = totalGridWidth; tableTOTAL.DisplayHeader = false; tableTOTAL.headerStyle.fontStyle = TableFontStyle.bold; tableTOTAL.headerStyle.fontSize = 8.5; tableTOTAL.headerStyle.fontName = "Tahoma"; tableTOTAL.headerStyle.fontStyle = TableFontStyle.bold; tableTOTAL.headerStyle.backgroundColor = Color.LightGray; tableTOTAL.column(0).width = checkAmountWidth; tableTOTAL.column(1).width = checkAmountValueWidth; tableTOTAL.addRow(); var cellTotalAmount = tableTOTAL.cell(tableTOTAL.rowCount - 1, 0); cellTotalAmount.style.fontStyle = TableFontStyle.bold; cellTotalAmount.style.fontName = "Tahoma"; cellTotalAmount.SetValue("Check Amount:"); cellTotalAmount.style.textAlign = TextAlignment.right; cellTotalAmount.style.borderColor = Color.Black; var cellTotalValue = tableTOTAL.cell(tableTOTAL.rowCount - 1, 1); cellTotalValue.style.fontStyle = TableFontStyle.bold; cellTotalValue.style.fontName = "Tahoma"; cellTotalValue.style.fontColor = Color.DarkRed; cellTotalValue.style.textAlign = TextAlignment.center; cellTotalValue.style.borderColor = Color.Black; cellTotalValue.SetValue("$" + totalCheckAmount.ToString("N")); cellTotalValue.style.fontColor = Color.DarkRed; lastHeigth -= 28; //double pageHeigth = document.PageSetupInfo.PageHeight - document.PageSetupInfo.TopMargin - document.PageSetupInfo.BottomMargin; //if (totalRowsCount <= 15) //{ document.CurrentPage.Body.DrawTable(tableTOTAL, totalTableEndX + tableXStart, lastHeigth); //} //else if (totalRowsCount > 15 && totalRowsCount <= 18) //{ // document.Pages[1].Body.DrawTable(tableTOTAL, totalTableEndX, 300); //} //else //count >15 //{ // double yPosition = (totalRowsCount - 15) * 24 + 20; // document.Pages[1].Body.DrawTable(tableTOTAL, totalTableEndX, yPosition); //} //??? //end table #region footer for (int i = 0; i < document.PageCount; i++) { document.Pages[i].Footer.SetActiveFont("Tahoma", PDFFontStyles.Regular, 9); if (!string.IsNullOrEmpty(_settings.CompanyDetails)) { var lines = _settings.CompanyDetails.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); string display = string.Empty; if (lines.Length > 0) { display = lines[0]; } else { display = _settings.CompanyDetails; } display += System.Environment.NewLine + datCurrentDate.Value.ToString("MM/dd/yyyy"); document.Pages[i].Footer.AddTextArea(new RectangleF(0, 0, 150, 30), display, false); } document.Pages[i].Footer.AddTextArea(new RectangleF(240, 0, 250, 50), _settings.SoftwareProvider, false); document.Pages[i].Footer.AddTextArea(new RectangleF(513, 0, 100, 30), string.Format("page {0} of {1}", i + 1, document.PageCount), false); } #endregion document.Save(); pdfOutput = outputMs.ToArray(); } } string filename = DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss"); try { File.WriteAllBytes(filename + ".pdf", pdfOutput); Process.Start(filename + ".pdf"); } catch (Exception ex) { MessageBox.Show("The file is already open!"); } string exportString = JsonConvert.SerializeObject(exportdata); if (!Directory.Exists("Export")) { Directory.CreateDirectory("Export"); } File.WriteAllText(string.Format("Export/{0}.txt", filename), exportString); } catch (Exception ex) { MessageBox.Show(ex.Message); } }