internal override void Render() { RenderFilling(); ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; Area contentArea = this.renderInfo.LayoutInfo.ContentArea; XRect destRect = new XRect(contentArea.X, contentArea.Y, formatInfo.Width, formatInfo.Height); if (formatInfo.failure == ImageFailure.None) { XImage xImage = null; try { XRect srcRect = new XRect(formatInfo.CropX, formatInfo.CropY, formatInfo.CropWidth, formatInfo.CropHeight); xImage = XImage.FromFile(formatInfo.ImagePath); this.gfx.DrawImage(xImage, destRect, srcRect, XGraphicsUnit.Point); //Pixel. } catch (Exception) { RenderFailureImage(destRect); } finally { if (xImage != null) { xImage.Dispose(); } } } else { RenderFailureImage(destRect); } RenderLine(); }
private void CalculateImageDimensions() { ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; if (formatInfo.failure == ImageFailure.None) { XImage xImage = null; try { xImage = XImage.FromFile(this.imageFilePath); } catch (InvalidOperationException ex) { Trace.WriteLine(Messages.InvalidImageType(ex.Message)); formatInfo.failure = ImageFailure.InvalidType; } try { XUnit usrWidth = image.Width.Point; XUnit usrHeight = image.Height.Point; bool usrWidthSet = !this.image.IsNull("Width"); bool usrHeightSet = !this.image.IsNull("Height"); XUnit resultWidth = usrWidth; XUnit resultHeight = usrHeight; double xPixels = xImage.PixelWidth; bool usrResolutionSet = !image.IsNull("Resolution"); double horzRes = usrResolutionSet ? (double)image.Resolution : xImage.HorizontalResolution; XUnit inherentWidth = XUnit.FromInch(xPixels / horzRes); double yPixels = xImage.PixelHeight; double vertRes = usrResolutionSet ? (double)image.Resolution : xImage.VerticalResolution; XUnit inherentHeight = XUnit.FromInch(yPixels / vertRes); bool lockRatio = this.image.IsNull("LockAspectRatio") ? true : image.LockAspectRatio; double scaleHeight = this.image.ScaleHeight; double scaleWidth = this.image.ScaleWidth; bool scaleHeightSet = !this.image.IsNull("ScaleHeight"); bool scaleWidthSet = !this.image.IsNull("ScaleWidth"); if (lockRatio && !(scaleHeightSet && scaleWidthSet)) { if (usrWidthSet && !usrHeightSet) { resultHeight = inherentHeight / inherentWidth * usrWidth; } else if (usrHeightSet && !usrWidthSet) { resultWidth = inherentWidth / inherentHeight * usrHeight; } else if (!usrHeightSet && !usrWidthSet) { resultHeight = inherentHeight; resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; resultWidth = resultWidth * scaleHeight; } if (scaleWidthSet) { resultHeight = resultHeight * scaleWidth; resultWidth = resultWidth * scaleWidth; } } else { if (!usrHeightSet) { resultHeight = inherentHeight; } if (!usrWidthSet) { resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; } if (scaleWidthSet) { resultWidth = resultWidth * scaleWidth; } } formatInfo.CropWidth = (int)xPixels; formatInfo.CropHeight = (int)yPixels; if (!this.image.IsNull("PictureFormat")) { PictureFormat picFormat = this.image.PictureFormat; //Cropping in pixels. XUnit cropLeft = picFormat.CropLeft.Point; XUnit cropRight = picFormat.CropRight.Point; XUnit cropTop = picFormat.CropTop.Point; XUnit cropBottom = picFormat.CropBottom.Point; formatInfo.CropX = (int)(horzRes * cropLeft.Inch); formatInfo.CropY = (int)(vertRes * cropTop.Inch); formatInfo.CropWidth -= (int)(horzRes * ((XUnit)(cropLeft + cropRight)).Inch); formatInfo.CropHeight -= (int)(vertRes * ((XUnit)(cropTop + cropBottom)).Inch); //Scaled cropping of the height and width. double xScale = resultWidth / inherentWidth; double yScale = resultHeight / inherentHeight; cropLeft = xScale * cropLeft; cropRight = xScale * cropRight; cropTop = yScale * cropTop; cropBottom = yScale * cropBottom; resultHeight = resultHeight - cropTop - cropBottom; resultWidth = resultWidth - cropLeft - cropRight; } if (resultHeight <= 0 || resultWidth <= 0) { formatInfo.Width = XUnit.FromCentimeter(2.5); formatInfo.Height = XUnit.FromCentimeter(2.5); Trace.WriteLine(Messages.EmptyImageSize); this.failure = ImageFailure.EmptySize; } else { formatInfo.Width = resultWidth; formatInfo.Height = resultHeight; } } catch (Exception ex) { Trace.WriteLine(Messages.ImageNotReadable(this.image.Name, ex.Message)); formatInfo.failure = ImageFailure.NotRead; } finally { if (xImage != null) { xImage.Dispose(); } } } if (formatInfo.failure != ImageFailure.None) { if (!this.image.IsNull("Width")) { formatInfo.Width = this.image.Width.Point; } else { formatInfo.Width = XUnit.FromCentimeter(2.5); } if (!this.image.IsNull("Height")) { formatInfo.Height = this.image.Height.Point; } else { formatInfo.Height = XUnit.FromCentimeter(2.5); } return; } }
private void CalculateImageDimensions() { ImageFormatInfo formatInfo = (ImageFormatInfo)_renderInfo.FormatInfo; if (formatInfo.Failure == ImageFailure.None) { XImage xImage = null; try { //xImage = XImage.FromFile(_imageFilePath); xImage = CreateXImage(_imageFilePath); } catch (InvalidOperationException ex) { Debug.WriteLine(Messages2.InvalidImageType(ex.Message)); formatInfo.Failure = ImageFailure.InvalidType; } if (formatInfo.Failure == ImageFailure.None) { try { XUnit usrWidth = _image.Width.Point; XUnit usrHeight = _image.Height.Point; bool usrWidthSet = !_image._width.IsNull; bool usrHeightSet = !_image._height.IsNull; XUnit resultWidth = usrWidth; XUnit resultHeight = usrHeight; Debug.Assert(xImage != null); double xPixels = xImage.PixelWidth; bool usrResolutionSet = !_image._resolution.IsNull; double horzRes = usrResolutionSet ? _image.Resolution : xImage.HorizontalResolution; double vertRes = usrResolutionSet ? _image.Resolution : xImage.VerticalResolution; // ReSharper disable CompareOfFloatsByEqualityOperator if (horzRes == 0 && vertRes == 0) { horzRes = 72; vertRes = 72; } else if (horzRes == 0) { Debug.Assert(false, "How can this be?"); horzRes = 72; } else if (vertRes == 0) { Debug.Assert(false, "How can this be?"); vertRes = 72; } // ReSharper restore CompareOfFloatsByEqualityOperator XUnit inherentWidth = XUnit.FromInch(xPixels / horzRes); double yPixels = xImage.PixelHeight; XUnit inherentHeight = XUnit.FromInch(yPixels / vertRes); //bool lockRatio = _image.IsNull("LockAspectRatio") ? true : _image.LockAspectRatio; bool lockRatio = _image._lockAspectRatio.IsNull || _image.LockAspectRatio; double scaleHeight = _image.ScaleHeight; double scaleWidth = _image.ScaleWidth; //bool scaleHeightSet = !_image.IsNull("ScaleHeight"); //bool scaleWidthSet = !_image.IsNull("ScaleWidth"); bool scaleHeightSet = !_image._scaleHeight.IsNull; bool scaleWidthSet = !_image._scaleWidth.IsNull; if (lockRatio && !(scaleHeightSet && scaleWidthSet)) { if (usrWidthSet && !usrHeightSet) { resultHeight = inherentHeight / inherentWidth * usrWidth; } else if (usrHeightSet && !usrWidthSet) { resultWidth = inherentWidth / inherentHeight * usrHeight; } // ReSharper disable once ConditionIsAlwaysTrueOrFalse else if (!usrHeightSet && !usrWidthSet) { resultHeight = inherentHeight; resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; resultWidth = resultWidth * scaleHeight; } if (scaleWidthSet) { resultHeight = resultHeight * scaleWidth; resultWidth = resultWidth * scaleWidth; } } else { if (!usrHeightSet) { resultHeight = inherentHeight; } if (!usrWidthSet) { resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; } if (scaleWidthSet) { resultWidth = resultWidth * scaleWidth; } } formatInfo.CropWidth = (int)xPixels; formatInfo.CropHeight = (int)yPixels; if (_image._pictureFormat != null && !_image._pictureFormat.IsNull()) { PictureFormat picFormat = _image.PictureFormat; //Cropping in pixels. XUnit cropLeft = picFormat.CropLeft.Point; XUnit cropRight = picFormat.CropRight.Point; XUnit cropTop = picFormat.CropTop.Point; XUnit cropBottom = picFormat.CropBottom.Point; formatInfo.CropX = (int)(horzRes * cropLeft.Inch); formatInfo.CropY = (int)(vertRes * cropTop.Inch); formatInfo.CropWidth -= (int)(horzRes * ((XUnit)(cropLeft + cropRight)).Inch); formatInfo.CropHeight -= (int)(vertRes * ((XUnit)(cropTop + cropBottom)).Inch); //Scaled cropping of the height and width. double xScale = resultWidth / inherentWidth; double yScale = resultHeight / inherentHeight; cropLeft = xScale * cropLeft; cropRight = xScale * cropRight; cropTop = yScale * cropTop; cropBottom = yScale * cropBottom; resultHeight = resultHeight - cropTop - cropBottom; resultWidth = resultWidth - cropLeft - cropRight; } if (resultHeight <= 0 || resultWidth <= 0) { formatInfo.Width = XUnit.FromCentimeter(2.5); formatInfo.Height = XUnit.FromCentimeter(2.5); Debug.WriteLine(Messages2.EmptyImageSize); _failure = ImageFailure.EmptySize; } else { formatInfo.Width = resultWidth; formatInfo.Height = resultHeight; } } catch (Exception ex) { Debug.WriteLine(Messages2.ImageNotReadable(_image.Name, ex.Message)); formatInfo.Failure = ImageFailure.NotRead; } finally { if (xImage != null) { xImage.Dispose(); } } } } if (formatInfo.Failure != ImageFailure.None) { if (!_image._width.IsNull) { formatInfo.Width = _image.Width.Point; } else { formatInfo.Width = XUnit.FromCentimeter(2.5); } if (!_image._height.IsNull) { formatInfo.Height = _image.Height.Point; } else { formatInfo.Height = XUnit.FromCentimeter(2.5); } } }
void ImagesFoldersToPdf(List <string> images, string outputFolderPath, string outputFileName) { PdfDocument ouput = new PdfDocument(); foreach (string image in images) { XImage im = XImage.FromFile(image); if (File.Exists("temp.png")) { File.Delete("temp.png"); } var bitmap = Bitmap.FromFile(image); switch (comboBox1.SelectedIndex) { case 0: break; case 1: bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 2: bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 3: bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } if (im.Width > im.Height) { bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone); } bitmap.Save("temp.png", ImageFormat.Png); im.Dispose(); bitmap.Dispose(); XImage img = XImage.FromFile("temp.png"); // each source file saeparate PdfDocument doc = new PdfDocument(); PdfPage p = new PdfPage(); double width = img.Width; double height = img.Height; double w = 0, h = 0; double rate = width / height; double x = 0, y = 0; if (rate < (p.Width / p.Height)) { //p.Orientation = PdfSharp.PageOrientation.Portrait; h = p.Height; w = rate * h; x = (p.Width - w) / 2; } else { //p.Orientation = PdfSharp.PageOrientation.Landscape; w = p.Width; h = w / rate; y = (p.Height - h) / 2; } doc.Pages.Add(p); XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]); xgr.DrawImage(img, x, y, w, h); img.Dispose(); xgr.Dispose(); // save to destination file FileInfo fi = new FileInfo("temp.png"); doc.Save(fi.FullName.Replace(fi.Extension, ".PDF")); PdfDocument inputDocument = PdfReader.Open(fi.FullName.Replace(fi.Extension, ".PDF"), PdfDocumentOpenMode.Import); PdfPage page = inputDocument.Pages[0]; ouput.AddPage(page); File.Delete(fi.FullName.Replace(fi.Extension, ".PDF")); doc.Close(); doc.Dispose(); } ouput.Save(string.Format("{0}\\{1}", outputFolderPath, outputFileName)); ouput.Close(); ouput.Dispose(); GC.Collect(); }
bool IMessageFilter.PreFilterMessage(ref Message m) { TwainCommand cmd = tw.PassMessage(ref m); if (cmd == TwainCommand.Not) { return(false); } switch (cmd) { case TwainCommand.CloseRequest: { // _Mensaje = "CloseRequest"; EndingScan(); tw.CloseSrc(); break; } case TwainCommand.CloseOk: { // _Mensaje = "CloseOk"; EndingScan(); tw.CloseSrc(); break; } case TwainCommand.DeviceEvent: { // _Mensaje = "DeviceEvent"; break; } case TwainCommand.Null: { // _Mensaje = "Null"; EndingScan(); tw.CloseSrc(); break; } case TwainCommand.TransferReady: { _Mensaje = "TransferReady"; ArrayList pics = tw.TransferPictures(); EndingScan(); tw.CloseSrc(); if (pics.Count == 0) { _Mensaje = "NoHojas"; return(true); } // picnumber++; quitar //inicializacion de clase para guardar imagen Escaner.Escaner objEscaner = new Escaner.Escaner(); //crea el documento pdf donde se le agregaran hojas PdfDocument documento = new PdfDocument(); for (int i = 0; i < pics.Count; i++) { IntPtr img = (IntPtr)pics[i]; //var que contiene la imagen actual int picnum = i + 1; objEscaner.GuardaImagen(img, _dir, _nombre + picnum.ToString()); //codigo para crear pdf PdfPage hoja = documento.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(hoja); XImage jpg = XImage.FromFile(_dir + _nombre + picnum.ToString() + ".jpg"); gfx.DrawImage(jpg, 0, 0, hoja.Width, hoja.Height); jpg.Dispose(); //para poder eliminar la foto File.Delete(_dir + _nombre + picnum.ToString() + ".jpg"); //fin codigo para grear PDF } //ya con todas las paginas agregadas cuarda el archivo pdf; if (documento.PageCount > 0) { documento.Save(_dir + _nombre + ".pdf"); } documento.Dispose(); if (_destino == @"\") { _destino = _dir; } File.Move(_dir + _nombre + ".pdf", _destino + _nombre + ".pdf"); _Mensaje = "TransferReadyFin"; return(true); } } return(true); }
private void CalculateImageDimensions() { XImage bip = null; try { _imageFile = File.OpenRead(_filePath); //System.Drawing.Bitmap bip2 = new System.Drawing.Bitmap(imageFile); bip = XImage.FromFile(_filePath); float horzResolution; float vertResolution; string ext = Path.GetExtension(_filePath).ToLower(); float origHorzRes = (float)bip.HorizontalResolution; float origVertRes = (float)bip.VerticalResolution; _originalHeight = bip.PixelHeight * 72 / origVertRes; _originalWidth = bip.PixelWidth * 72 / origHorzRes; if (_image.IsNull("Resolution")) { horzResolution = (ext == ".gif") ? 72 : (float)bip.HorizontalResolution; vertResolution = (ext == ".gif") ? 72 : (float)bip.VerticalResolution; } else { horzResolution = (float)GetValueAsIntended("Resolution"); vertResolution = horzResolution; } Unit origHeight = bip.Size.Height * 72 / vertResolution; Unit origWidth = bip.Size.Width * 72 / horzResolution; _imageHeight = origHeight; _imageWidth = origWidth; bool scaleWidthIsNull = _image.IsNull("ScaleWidth"); bool scaleHeightIsNull = _image.IsNull("ScaleHeight"); float sclHeight = scaleHeightIsNull ? 1 : (float)GetValueAsIntended("ScaleHeight"); _scaleHeight = sclHeight; float sclWidth = scaleWidthIsNull ? 1 : (float)GetValueAsIntended("ScaleWidth"); _scaleWidth = sclWidth; bool doLockAspectRatio = _image.IsNull("LockAspectRatio") || _image.LockAspectRatio; if (doLockAspectRatio && (scaleHeightIsNull || scaleWidthIsNull)) { if (!_image.IsNull("Width") && _image.IsNull("Height")) { _imageWidth = _image.Width; _imageHeight = origHeight * _imageWidth / origWidth; } else if (!_image.IsNull("Height") && _image.IsNull("Width")) { _imageHeight = _image.Height; _imageWidth = origWidth * _imageHeight / origHeight; } else if (!_image.IsNull("Height") && !_image.IsNull("Width")) { _imageWidth = _image.Width; _imageHeight = _image.Height; } if (scaleWidthIsNull && !scaleHeightIsNull) { _scaleWidth = _scaleHeight; } else if (scaleHeightIsNull && !scaleWidthIsNull) { _scaleHeight = _scaleWidth; } } else { if (!_image.IsNull("Width")) { _imageWidth = _image.Width; } if (!_image.IsNull("Height")) { _imageHeight = _image.Height; } } return; } catch (FileNotFoundException) { Debug.WriteLine(Messages2.ImageNotFound(_image.Name), "warning"); } catch (Exception exc) { Debug.WriteLine(Messages2.ImageNotReadable(_image.Name, exc.Message), "warning"); } finally { if (bip != null) { bip.Dispose(); } } //Setting defaults in case an error occured. _imageFile = null; _imageHeight = (Unit)GetValueOrDefault("Height", Unit.FromInch(1)); _imageWidth = (Unit)GetValueOrDefault("Width", Unit.FromInch(1)); _scaleHeight = (double)GetValueOrDefault("ScaleHeight", 1.0); _scaleWidth = (double)GetValueOrDefault("ScaleWidth", 1.0); }
/// <summary> /// Obtem o caminho do PDF a partir do cadastro do faturamento no banco de dados, e se nao preenchido, faz download e update no campo /// </summary> /// <param name="aintTipo">1 = caminho local (c:\...) | 2 = Url completo (http://...) | 3 = Url relativa</param> /// <returns></returns> public string getCaminhoPdfNf(int aintTipo) { string lstrRet = this.CaminhoPdfNf; if (string.IsNullOrEmpty(lstrRet)) { if (EmpresaEmissao == null) { EmpresaEmissao = new Empresa(); } if (EmpresaEmissaoID > 0 && EmpresaEmissao.ID == 0) { EmpresaEmissao.ID = EmpresaEmissaoID; } if (EmpresaEmissao.ID > 0 && string.IsNullOrEmpty(EmpresaEmissao.CcmPmsp)) { Empresa lobjEmpDB = m_empresaRepository.All.Where(p => p.ID == EmpresaEmissao.ID).FirstOrDefault <Empresa>(); if (lobjEmpDB != null) { EmpresaEmissao = lobjEmpDB; } } if (NumeroNF == null || NumeroNF == 0 || string.IsNullOrEmpty(CodigoVerificacao) || string.IsNullOrEmpty(EmpresaEmissao.CcmPmsp)) { throw new Exception("Não é possível baixar a nota fiscal porque um dos seguintes campos campos vazios: numero da nota, codigo de verificacao ou CCM da emissor"); } else { lstrRet = AppDomain.CurrentDomain.BaseDirectory + @"\Arquivos\PdfNotaFiscal\"; if (Directory.Exists(lstrRet) == false) { Directory.CreateDirectory(lstrRet); } lstrRet += "NF" + NumeroNF + "CCM" + EmpresaEmissao.CcmPmsp + "VERIF" + CodigoVerificacao + ".gif"; if (File.Exists(lstrRet)) { File.Delete(lstrRet); } new WebClient().DownloadFile(getUrlLinkNfSitePmsp(), lstrRet); Image img = Image.FromFile(lstrRet); int lintNovoWidth = 1000; int lintNovoHeight = 1000; int lintOrigWidth = img.Width; // largura original int lintOrigHeight = img.Height; // altura original // redimensiona se necessario if (lintOrigWidth > lintNovoWidth || lintOrigHeight > lintNovoHeight) { if (lintOrigWidth > lintOrigHeight) { // imagem horizontal lintNovoHeight = (lintOrigHeight * lintNovoWidth) / lintOrigWidth; } else { // imagem vertical lintNovoWidth = (lintOrigWidth * lintNovoHeight) / lintOrigHeight; } } Bitmap newImage = new Bitmap(lintNovoWidth, lintNovoHeight); using (Graphics gr = Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(img, new Rectangle(0, 0, lintNovoWidth, lintNovoHeight)); } lstrRet = lstrRet.Replace(".gif", ".jpg"); if (File.Exists(lstrRet)) { File.Delete(lstrRet); } newImage.SetResolution(96, 96); newImage.Save(lstrRet, ImageFormat.Jpeg); PdfDocument lobjPdfMatriz = new PdfDocument(); PdfPage lobjPagina = lobjPdfMatriz.Pages.Add(); XGraphics lobjGraphics = XGraphics.FromPdfPage(lobjPagina); if (File.Exists(lstrRet)) { XImage lobjLogo = XImage.FromFile(lstrRet); lobjGraphics.DrawImage(lobjLogo, 10, 10); lobjLogo.Dispose(); lobjLogo = null; } lobjPdfMatriz.Close(); lstrRet = lstrRet.Replace(".jpg", ".pdf"); if (File.Exists(lstrRet)) { File.Delete(lstrRet); } lobjPdfMatriz.Save(lstrRet); CaminhoPdfNf = lstrRet; if (this.ID > 0) { Faturamento lobjFatUpdate = m_faturamentoRepository.All.Where(p => p.ID == this.ID).FirstOrDefault <Faturamento>(); if (lobjFatUpdate != null) { lobjFatUpdate.CaminhoPdfNf = lstrRet; m_faturamentoRepository.InsertOrUpdate(lobjFatUpdate); m_faturamentoRepository.Save(); } } } } if (File.Exists(lstrRet) && lstrRet.ToLower().StartsWith(AppDomain.CurrentDomain.BaseDirectory.ToLower())) { if (aintTipo == 2) { lstrRet = CaminhoPdfNf.Substring(AppDomain.CurrentDomain.BaseDirectory.Length); } else if (aintTipo == 3) { } } else { lstrRet = string.Empty; } return(lstrRet); }
private void JPGaPDF(string ruta, string nombreArchivo) { string archivo = ruta + "\\" + nombreArchivo + ".pdf"; PdfDocument s_document = new PdfDocument(); PdfPage page; s_document.Info.CreationDate = DateTime.Now; s_document.ViewerPreferences.FitWindow = true; s_document.Info.Title = nombreArchivo; s_document.Info.Author = "Xawan Solutions"; if (File.Exists(archivo)) { if (MessageBox.Show("El archivo ya existe. \n¿Desea sobreescribirlo?", "Pregunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { this.Cursor = Cursors.WaitCursor; for (int i = 0; i < listaImagenes.Items.Count; i++) { page = s_document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XImage image = XImage.FromFile(listaImagenes.Items[i].SubItems[0].Text); page.Width = image.PixelWidth; page.Height = image.PixelHeight; gfx.DrawImage(image, 0, 0, image.PixelWidth, image.PixelHeight); gfx.Dispose(); image.Dispose(); } // Save the s_document... s_document.Save(archivo); MessageBox.Show("Archivo guardado en: " + archivo, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Cursor = Cursors.Default; if (checkTab1Abrir.Checked) { // ...and start a viewer Process.Start(archivo); } } else { txtNombreArchivo.Focus(); txtNombreArchivo.SelectionStart = 0; txtNombreArchivo.SelectionLength = txtNombreArchivo.Text.Length; } } else { this.Cursor = Cursors.WaitCursor; for (int i = 0; i < listaImagenes.Items.Count; i++) { page = s_document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XImage image = XImage.FromFile(listaImagenes.Items[i].SubItems[0].Text); page.Width = image.PixelWidth; page.Height = image.PixelHeight; gfx.DrawImage(image, 0, 0, image.PixelWidth, image.PixelHeight); gfx.Dispose(); image.Dispose(); } // Save the s_document... s_document.Save(archivo); MessageBox.Show("Archivo guardado en: " + archivo, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Cursor = Cursors.Default; if (checkTab1Abrir.Checked) { // ...and start a viewer Process.Start(archivo); } } }
public void btnConvertirPDF_Click(object sender, EventArgs e) { if (listView1.Items.Count > 0) { oPicLoading.Visible = true; lblProcesando.Visible = true; string fileName = ""; string completeFileName = ""; string path = Metodos_Globales.crearCarpetaAppdata("\\SoftNet G-Clinic\\TempFiles"); try { fileName = "\\TempFile_PDF.pdf"; completeFileName = path + fileName; File.Delete(completeFileName); } catch { MessageBox.Show(this, "No se puede crear el archivo/reporte ya que otro está actualmente en uso, cierre el archivo temporal en uso primero y vuelva a intentar", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } double xPos = 0; double yPos = 0; PdfDocument doc = new PdfDocument(); int cont = 0; #region MyRegion //foreach (GlobalElementsValues oElement in softNetImageViewer3.GlobalElementsDetails) //{ // Application.DoEvents(); // doc.Pages.Add(new PdfPage()); // XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[cont]); // XImage img = XImage.FromFile(oElement.OFileName); // XSize oSize = ImageSize(doc.Pages[cont], img); // if (doc.Pages[cont].Width > img.PointWidth) // xPos = (doc.Pages[cont].Width - img.PointWidth) / 2; // else // xPos = (img.PointWidth - doc.Pages[cont].Width) / 2; // yPos = (doc.Pages[cont].Height - img.PointHeight) / 2; // xgr.DrawImage(img, xPos, yPos, oSize.Width, oSize.Height); // xgr.Dispose(); // img.Dispose(); // cont++; //} #endregion string filename = textBox1.Text.Trim(); foreach (ListViewItem oItem in listView1.Items) { Application.DoEvents(); doc.Pages.Add(new PdfPage()); XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[cont]); //string path1 = ConvertImage(File.ReadAllBytes(filename + "\\" + oItem.Text.Trim()), doc.Pages[cont]); XImage img = XImage.FromFile(filename + "\\" + oItem.Text.Trim()); //oElement.OFileName);//path1) ; XSize oSize = ImageSize(doc.Pages[cont], img); //img.Size; //img.Size.Height = oSize.Height; if (doc.Pages[cont].Width > oSize.Width) //img.PointWidth) { xPos = (doc.Pages[cont].Width - oSize.Width) / 2; //img.PointWidth) / 2; } else { xPos = (oSize.Width - doc.Pages[cont].Width) / 2; //(img.PointWidth - doc.Pages[cont].Width) / 2; } yPos = (doc.Pages[cont].Height - oSize.Height) / 2; //img.PointHeight) / 2; xgr.DrawImage(img, xPos, yPos, oSize.Width, oSize.Height); xgr.Dispose(); img.Dispose(); xgr = null; img = null; cont++; //File.Delete(path1); } try { doc.Save(completeFileName); } catch { MessageBox.Show(this, "No se puede generar el archivo si no hay imágenes disponibles", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error); } doc.Close(); doc.Dispose(); oPicLoading.Visible = false; lblProcesando.Visible = false; softNet_AdobePDFViewer1.FileLocation = completeFileName; softNet_AdobePDFViewer1.OpenDocument(); } else { MessageBox.Show(this, "No se puede generar el archivo si no hay imágenes disponibles", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void PrintAsPDFAfterTilesAreLoaded() { AxMap.TilesLoaded -= AxMap_TilesLoaded; string localdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ResTBDesktop"; string localappdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\ResTBDesktop"; PdfDocument mapTemplate = PdfReader.Open(localappdata + "\\PrintTemplates\\A4_landscape.pdf", PdfDocumentOpenMode.Modify); PdfDocument outputDocument = new PdfDocument(); outputDocument.PageLayout = mapTemplate.PageLayout; PdfPage page = outputDocument.AddPage(); page.Orientation = mapTemplate.Pages[0].Orientation; page.Width = mapTemplate.Pages[0].Width; page.Height = mapTemplate.Pages[0].Height; int dx = (int)page.Width.Point, dy = (int)page.Height.Point; // calculate aspect var diffX = AxMap.Extents.xMax - AxMap.Extents.xMin; double aspect = ((double)dy / dx); int diffY = (int)(aspect * diffX); // start tile loading for cache Extents MapExtents = new Extents(); MapExtents.SetBounds(AxMap.Extents.xMin, AxMap.Extents.yMin, AxMap.Extents.zMin, AxMap.Extents.xMax, AxMap.Extents.yMin + diffY, AxMap.Extents.zMax); // scale double meter = AxMap.GeodesicDistance(AxMap.Extents.xMin, AxMap.Extents.yMin, AxMap.Extents.xMax, AxMap.Extents.yMin); double pageWidthInMeter = ((page.Width / 72) * 2.54) / 100; int scale = (int)(meter / pageWidthInMeter); int scaleRounded = scale % 100 >= 50 ? scale + 100 - scale % 100 : scale - scale % 100; if ((scale - scaleRounded < 10) && (scale - scaleRounded > -10)) { scale = scaleRounded; } // Load the template stuff and change the acroforms... PdfAcroForm acroform = mapTemplate.AcroForm; if (acroform.Elements.ContainsKey("/NeedAppearances")) { acroform.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true); } else { acroform.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true)); } var name = (PdfTextField)(acroform.Fields["ProjectTitle"]); changeFont(name, 12); name.Value = new PdfString(project.Name); var numberlabel = (PdfTextField)(acroform.Fields["ProjectNumberLabel"]); changeFont(numberlabel, 7); numberlabel.Value = new PdfString(Resources.Project_Number); var number = (PdfTextField)(acroform.Fields["ProjectNumber"]); changeFont(number, 7); number.Value = new PdfString(project.Number); var descriptionlabel = (PdfTextField)(acroform.Fields["DescriptionLabel"]); changeFont(descriptionlabel, 7); descriptionlabel.Value = new PdfString(Resources.Description); var description = (PdfTextField)(acroform.Fields["Description"]); changeFont(description, 7); description.Value = new PdfString(project.Description); var scalefield = (PdfTextField)(acroform.Fields["Scale"]); changeFont(scalefield, 10); scalefield.Value = new PdfString("1 : " + (int)scale); var legend = (PdfTextField)(acroform.Fields["LegendLabel"]); legend.Value = new PdfString(Resources.Legend); var copyright = (PdfTextField)(acroform.Fields["CopyrightLabel"]); copyright.Value = new PdfString("Impreso con " + Resources.App_Name); mapTemplate.Flatten(); mapTemplate.Save(localdata + "\\printtemp.pdf"); mapTemplate.Close(); XGraphics gfx = XGraphics.FromPdfPage(page); var imageFromMap = AxMap.SnapShot3(AxMap.Extents.xMin, AxMap.Extents.xMax, AxMap.Extents.yMin + diffY, AxMap.Extents.yMin, (int)(dx * (96.0 / 72.0) * 2)); imageFromMap.Save(localdata + "\\printTemp.tif", false, ImageType.TIFF_FILE); XImage image = XImage.FromFile(localdata + "\\printTemp.tif"); // Left position in point double x = (dx - image.PixelWidth * 72 / image.HorizontalResolution) / 2; gfx.DrawImage(image, 0, 0, dx, dy); /* * XImage mapLayout = XImage.FromFile(localdata + "\\PrintTemplates\\A4_quer.png"); * * * double width = mapLayout.PixelWidth * 72 / mapLayout.HorizontalResolution; * double height = mapLayout.PixelHeight * 72 / mapLayout.HorizontalResolution; * * gfx.DrawImage(mapLayout, (dx - width) / 2, (dy - height) / 2, width, height); */ //outputDocument.AddPage(mapTemplateFilledOut.Pages[0]); XPdfForm form = XPdfForm.FromFile(localdata + "\\printtemp.pdf"); gfx.DrawImage(form, 0, 0); outputDocument.Save(filename); image.Dispose(); Process.Start(filename); }
private void buttonScanPages_Click(object sender, RoutedEventArgs e) { // select device if this failed at startup if (string.IsNullOrEmpty(_deviceId)) { if (!SelectDevice()) { return; } } try { Mouse.OverrideCursor = Cursors.Wait; _width = Convert.ToDouble(textBoxWidth.Text, CultureInfo.CurrentCulture); _height = Convert.ToDouble(textBoxHeight.Text, CultureInfo.CurrentCulture); _adf = (checkBoxADF.IsChecked == true); XImage ximage = null; while ((ximage = ScanOne()) != null) { PdfPage page = _doc.AddPage(); page.Width = XUnit.FromInch(_width); page.Height = XUnit.FromInch(_height); using (XGraphics g = XGraphics.FromPdfPage(page)) { g.DrawImage(ximage, 0, 0); ximage.Dispose(); } // flag that the document needs saving _docSaved = false; // only scan one page if not using the ADF if (!_adf) { break; } UpdateState(); } } catch (Exception ex) { Mouse.OverrideCursor = null; UserSettings.Settings.LogException(LogSeverity.Warning, "Failed to scan page", ex); CatfoodMessageBox.Show(MainWindow.MessageBoxIcon, this, string.Format(CultureInfo.InvariantCulture, "{0} ({1})", WiaErrorOrMessage(ex), _lastItem), "Failed to scan - Catfood PdfScan", CatfoodMessageBoxType.Ok, CatfoodMessageBoxIcon.Error, ex); } finally { Mouse.OverrideCursor = null; UpdateState(); } }
public bool ExportToPDF(string FileNamePDF, bool ShowFile) { string strFileTmpPdf = string.Empty; PdfDocument objDocument = null; FileInfo objFileInfo = null; PdfPage objPage = null; XImage objImage = null; try { // Create a new PDF document objDocument = new PdfDocument(); objDocument.Info.Title = "Criado por OPUS DIGITALIZADOR"; objDocument.Info.Author = "OPUS Comérico Exterior Ltda"; objDocument.Info.Creator = "OPUS DIGITALIZADOR"; //Se o diretório de PDF não existir eu o crio if (!Directory.Exists(System.Configuration.ConfigurationSettings.AppSettings["DIRPDF"].ToString())) { Directory.CreateDirectory(System.Configuration.ConfigurationSettings.AppSettings["DIRPDF"].ToString()); } strFileTmpPdf = System.Configuration.ConfigurationSettings.AppSettings["DIRPDF"].ToString() + FileNamePDF; foreach (string strFileName in System.IO.Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["DIRIMGSCANNER"].ToString() + FileNamePDF)) { objFileInfo = new FileInfo(strFileName); if (objFileInfo.Extension.ToUpper() == System.Configuration.ConfigurationSettings.AppSettings["EXTIMG"].ToString()) { // Create an empty page objPage = objDocument.AddPage(); // Get an XGraphics object for drawing objGfx = XGraphics.FromPdfPage(objPage); objImage = XImage.FromFile(strFileName); //double x = (250 - objImage.PixelWidth * 72 / objImage.HorizontalResolution) / 2; int x = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["BEGINX"].ToString()); int y = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["BEGINY"].ToString()); int largura = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["WIDTH"].ToString()); int altura = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["HEIGHT"].ToString()); objGfx.DrawImage(objImage, x, y, largura, altura); if (File.Exists(strFileTmpPdf)) { File.Delete(strFileTmpPdf); } objDocument.Save(strFileTmpPdf); } } if (ShowFile) { Process.Start(strFileTmpPdf); } return(true); } catch (Exception ex) { throw ex; } finally { objPage = null; objImage.Dispose(); objImage = null; objDocument.Dispose(); objDocument = null; objFileInfo = null; } }
private void btn_GenFiles_Click(object sender, EventArgs e) { c_PositionImages cp = new c_PositionImages(); List <Bitmap> bmplst = cp.createPositions(psl[cb_Scheme.SelectedIndex], picList, selectedDPI); FolderBrowserDialog fbd = new FolderBrowserDialog(); if (Properties.Settings.Default.s_LastDir != "" && Directory.Exists(Properties.Settings.Default.s_LastDir)) { fbd.SelectedPath = Properties.Settings.Default.s_LastDir; } fbd.ShowNewFolderButton = true; if (fbd.ShowDialog() == DialogResult.OK) { Properties.Settings.Default.s_LastDir = fbd.SelectedPath; Properties.Settings.Default.Save(); string path = fbd.SelectedPath; DateTime d = DateTime.Now; if (rb_PDF.Checked) { string fn = "pic_collage_pdf_" + d.Year + d.Month + d.Day + "_" + d.Hour + d.Minute + ".pdf"; using (PdfSharp.Pdf.PdfDocument pdoc = new PdfSharp.Pdf.PdfDocument()) { pdoc.PageLayout = PdfSharp.Pdf.PdfPageLayout.SinglePage; if (!Directory.Exists(fbd.SelectedPath)) { Directory.CreateDirectory(fbd.SelectedPath); } if (!Directory.Exists(fbd.SelectedPath + "\\tmp")) { Directory.CreateDirectory(fbd.SelectedPath + "\\tmp"); } foreach (Bitmap b in bmplst) { b.Save(fbd.SelectedPath + "\\tmp\\bmp_tmp_" + bmplst.IndexOf(b) + ".bmp"); PdfSharp.Pdf.PdfPage pag = pdoc.AddPage(); pag.Width = selectedDPI.width; pag.Height = selectedDPI.height; XGraphics gfx = XGraphics.FromPdfPage(pag); XImage image = XImage.FromFile(fbd.SelectedPath + "\\tmp\\bmp_tmp_" + bmplst.IndexOf(b) + ".bmp"); gfx.DrawImage(image, 0, 0, (int)pag.Width, (int)pag.Height); image.Dispose(); b.Dispose(); gfx.Dispose(); pag.Close(); } pdoc.Save(fbd.SelectedPath + "\\" + fn); } Directory.Delete(fbd.SelectedPath + "\\tmp", true); System.Diagnostics.Process.Start("explorer.exe", "/select, \"" + fbd.SelectedPath + "\\" + fn + "\""); } else { string fn = "bmp_" + d.Year + d.Month + d.Day + "_" + d.Hour + d.Minute + "_"; foreach (Bitmap b in bmplst) { b.Save(fbd.SelectedPath + "\\" + fn + bmplst.IndexOf(b) + ".bmp"); } System.Diagnostics.Process.Start("explorer.exe", "/select, \"" + fbd.SelectedPath + "\\" + fn + "0.bmp\""); } } GC.Collect(); }
public void Dispose() => BackgroundImage?.Dispose();
private void bw_DoWork(object sender, DoWorkEventArgs e) { try { string[] fNames = (e.Argument as string[]); if (checkBoxSeparate.Checked) { for (int i = 1; i < fNames.Length; i++) { // each source file saeparate PdfDocument doc = new PdfDocument(); toolStripStatusLabel1.Text = "Processing " + fNames[i]; doc.Pages.Add(new PdfPage()); doc.Pages[0].Size = PdfSharp.PageSize.A4; doc.Pages[0].Orientation = PdfSharp.PageOrientation.Landscape; XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]); XImage img = XImage.FromFile(fNames[i]); xgr.DrawImage(img, 0, 0, 842, 595); img.Dispose(); xgr.Dispose(); // save to destination file FileInfo fi = new FileInfo(fNames[i]); doc.Save(fi.FullName.Replace(fi.Extension, ".PDF")); doc.Close(); } } else { // single document PdfDocument doc = new PdfDocument(); for (int i = 1; i < fNames.Length; i++) { toolStripStatusLabel1.Text = "Processing " + fNames[i]; // each source on separate page doc.Pages.Add(new PdfPage()); XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[i - 1]); XImage img = XImage.FromFile(fNames[i]); xgr.DrawImage(img, 0, 0); img.Dispose(); xgr.Dispose(); } // save to destination file doc.Pages[0].Orientation = PdfSharp.PageOrientation.Portrait; doc.Pages[0].Size = PdfSharp.PageSize.A4; doc.Pages[0].Rotate = 0; doc.Save(fNames[0]); doc.Close(); } success = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public override void Dispose() { _image.Dispose(); }
private void JPGaPDF(string ruta) { foreach (ListViewItem itemLista in listaImagenes.Items) { string nombreArchivo = Path.GetFileNameWithoutExtension(itemLista.Text); string archivo = ruta + "\\" + nombreArchivo + ".pdf"; if (File.Exists(archivo)) { if (MessageBox.Show("El archivo " + archivo + " ya existe.\n¿Desea sobreescribirlo?", "Pregunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { this.Cursor = Cursors.WaitCursor; PdfDocument s_document = new PdfDocument(); PdfPage page; s_document.Info.CreationDate = DateTime.Now; s_document.ViewerPreferences.FitWindow = true; s_document.Info.Title = nombreArchivo; s_document.Info.Author = "Xawan Solutions"; page = s_document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XImage image = XImage.FromFile(itemLista.Text); page.Width = image.PixelWidth; page.Height = image.PixelHeight; gfx.DrawImage(image, 0, 0, image.PixelWidth, image.PixelHeight); gfx.Dispose(); image.Dispose(); try { s_document.Save(archivo); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { this.Cursor = Cursors.Default; } } } else { this.Cursor = Cursors.WaitCursor; PdfDocument s_document = new PdfDocument(); PdfPage page; s_document.Info.CreationDate = DateTime.Now; s_document.ViewerPreferences.FitWindow = true; s_document.Info.Title = nombreArchivo; s_document.Info.Author = "Xawan Solutions"; page = s_document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XImage image = XImage.FromFile(itemLista.Text); page.Width = image.PixelWidth; page.Height = image.PixelHeight; gfx.DrawImage(image, 0, 0, image.PixelWidth, image.PixelHeight); gfx.Dispose(); image.Dispose(); try { s_document.Save(archivo); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { this.Cursor = Cursors.Default; } } } if (MessageBox.Show("Operación completada.\nArchivos guardados en " + ruta + ".\n¿Desea abrir la carpeta de destino?", "Operación realizada", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Process.Start(ruta); } }