Example #1
0
        public stDoc ToRasterFormatExParameters(stDoc Doc, string ext, string label, stParameter[] parameters)
        {
            try
            {
                logger.DebugFormat("ToRasterFormatExParameters - INIT - {0} - ext: {1}, label: {2}", HttpContext.Current.Request.UserHostAddress, ext, label);

                AttachConversionMode mode = AttachConversionMode.Default;
                if (parameters != null && parameters.Length > 0 &&
                    parameters.Any(x => x.Name == stParameterOption.AttachMode))
                {
                    stParameter foundParameter = parameters.First(x => x.Name == stParameterOption.AttachMode);
                    if (int.TryParse(foundParameter.Value, out int val))
                    {
                        mode = (AttachConversionMode)val;
                    }
                }

                byte[] documentContent    = Convert.FromBase64String(Doc.Blob);
                byte[] pdfDocumentContent = PrintRedirectedService.ConvertToFormatLabeled(documentContent, Doc.FileExtension, ext, label, mode);
                return(new stDoc
                {
                    Blob = Convert.ToBase64String(pdfDocumentContent),
                    FileExtension = ext
                });
            }
            catch (Exception exception)
            {
                logger.Error(exception);
                throw;
            }
            finally
            {
                logger.DebugFormat("ToRasterFormatExParameters - END - {0}", HttpContext.Current.Request.UserHostAddress);
            }
        }
Example #2
0
        public byte[] Convert(byte[] fileSource, string filename, string extReq, AttachConversionMode mode)
        {
            try
            {
                using (Document doc = new Document())
                    using (MemoryStream ms = new MemoryStream())
                        using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
                            using (MemoryStream bitmapStream = new MemoryStream(fileSource))
                            {
                                doc.Open();
                                Bitmap bitmapImage = new Bitmap(bitmapStream);
                                int    bitmapPages = bitmapImage.GetFrameCount(FrameDimension.Page);
                                iTextSharpText.Image imageInstance;
                                for (int page = 0; page < bitmapPages; page++)
                                {
                                    bitmapImage.SelectActiveFrame(FrameDimension.Page, page);
                                    using (MemoryStream imageStream = new MemoryStream())
                                    {
                                        try
                                        {
                                            bitmapImage.Save(imageStream, ImageFormat.Png);
                                            imageInstance = iTextSharpText.Image.GetInstance(imageStream.GetBuffer());
                                        }
                                        catch
                                        {
                                            bitmapImage.Save(imageStream, ImageFormat.Tiff);
                                            imageInstance = iTextSharpText.Image.GetInstance(imageStream.GetBuffer());
                                        }
                                    }

                                    imageInstance.SetAbsolutePosition(0, 0);
                                    doc.NewPage(imageInstance);
                                    doc.PageSize.ToA4WithRotation();
                                    doc.Add(imageInstance);
                                }
                                doc.Close();
                                return(ms.ToDeepCopyArray());
                            }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw;
            }
        }
Example #3
0
        public byte[] Convert(byte[] fileSource, string fileExtension, string extReq, AttachConversionMode mode)
        {
            string fileName = Path.GetTempFileName();

            fileExtension = GetCorrectFileExtension(fileExtension);
            string destination = string.Concat(fileName, ".", extReq);

            try
            {
                string formattedExtension = string.Concat(".", fileExtension.Replace(".", string.Empty));
                fileName = string.Concat(fileName, formattedExtension);
                File.WriteAllBytes(fileName, fileSource);
                _logger.WriteInfo(new LogMessage(string.Concat("Convert -> fileName: ", fileExtension, " - extension: ", fileExtension, " to pdf")), LogCategories);

                if (!_converterService.ConvertToPdf(fileName, destination, (ConversionMode)mode))
                {
                    return(null);
                }
                return(File.ReadAllBytes(destination));
            }
            catch (Exception ex)
            {
                _logger.WriteError(new LogMessage(string.Concat("Convert -> error on convert item ", fileName, " to pdf")), ex, LogCategories);
                throw;
            }
            finally
            {
                try
                {
                    _logger.WriteDebug(new LogMessage(string.Concat("Convert -> deleting: {0}", fileName)), LogCategories);
                    File.Delete(fileName);
                    _logger.WriteDebug(new LogMessage(string.Concat("Convert -> deleting: {0}", destination)), LogCategories);
                    File.Delete(destination);
                }
                catch (Exception ex)
                {
                    _logger.WriteError(new LogMessage("Convert -> error on deleting pending files"), ex, LogCategories);
                }
            }
        }
 public byte[] Convert(byte[] fileSource, string fileExtension, string extReq, AttachConversionMode mode)
 {
     try
     {
         using (Document doc = new Document())
             using (MemoryStream ms = new MemoryStream())
                 using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
                 {
                     doc.Open();
                     Image imageInstance = Image.GetInstance(fileSource);
                     imageInstance.SetAbsolutePosition(0, 0);
                     doc.NewPage(imageInstance);
                     doc.PageSize.ToA4WithRotation();
                     doc.Add(imageInstance);
                     doc.Close();
                     return(ms.ToDeepCopyArray());
                 }
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
         throw;
     }
 }
 public byte[] ConvertWithParameters(byte[] fileToConvert, string fileExtension, AttachConversionMode mode)
 {
     try
     {
         logger.DebugFormat("ConvertWithParameters {0}, mode:{1}", fileExtension, mode);
         return(ConverterAssemblyLoader.GetConverter().Convert(fileToConvert, fileExtension, "pdf", mode));
     }
     catch (Exception ex)
     {
         logger.Error(ex);
         throw;
     }
 }
Example #6
0
 public byte[] Convert(byte[] fileSource, string fileExtension, string extReq, AttachConversionMode mode)
 {
     return(Convert(fileSource, _xmlFactory.GetDefaultXsl(), fileExtension, extReq));
 }
        public byte[] Convert(byte[] fileSource, string fileExtension, string extReq, AttachConversionMode mode)
        {
            byte[] retval = new byte[0];

            try
            {
                Exception toThrow  = null;
                var       fileName = Path.Combine(Path.GetTempPath(), "SC_" + Guid.NewGuid() + ".tmp");

                File.WriteAllBytes(fileName, fileSource);

                try
                {
                    IntPtr instance;

                    if (gsapi_new_instance(out instance, IntPtr.Zero) == 0)
                    {
                        string convertedFile = Path.Combine(Path.GetTempPath(), "SC_" + Guid.NewGuid() + ".tmp");

                        try
                        {
                            string[] parameters = new string[] {
                                "-dSAFER",
                                "-dBATCH",
                                "-dNOPAUSE",
                                "-sDEVICE=jpeg",
                                "-dFirstPage=1",
                                "-dLastPage=1",
                                "-dPDFFitPage",
                                string.Format("-sOutputFile={0}", convertedFile),
                                fileName,
                            };

                            int retCode = gsapi_init_with_args(instance, parameters.Length, parameters);

                            gsapi_exit(instance);

                            if (retCode == 0)
                            {
                                retval = File.ReadAllBytes(convertedFile);
                            }
                            else
                            {
                                throw new Exception("Error in file conversion.");
                            }
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }
                        finally
                        {
                            try { gsapi_delete_instance(instance); }
                            catch { }

                            try { File.Delete(convertedFile); }
                            catch { }
                        }
                    }
                }
                catch (Exception ex)
                {
                    toThrow = ex;
                }
                finally
                {
                    try { File.Delete(fileName); }
                    catch { }

                    if (toThrow != null)
                    {
                        throw toThrow;
                    }
                }
            }
            catch (Exception exx)
            {
                throw exx;
            }

            return(retval);
        }
 public byte[] Convert(byte[] blob, string fileExtension, string extReq, ConverterType converterType, AttachConversionMode mode = AttachConversionMode.Default)
 {
     ConverterServiceSvc.StampaConformeConverterClient svc = null;
     try
     {
         svc = new ConverterServiceSvc.StampaConformeConverterClient("StampaConformeConverter", PrintRedirectConfigurations.GetWsUrl(converterType, lastWs));
         //svc.Url = PrintRedirectConfigurations.GetWsUrl(lastWs);
         logger.InfoFormat("Call External WS: {0}", svc.Endpoint.ListenUri.ToString());
         byte[] res = null;
         if (mode == AttachConversionMode.Default)
         {
             res = svc.Convert(blob, fileExtension);
         }
         else
         {
             res = svc.ConvertWithParameters(blob, fileExtension, (ConverterServiceSvc.AttachConversionMode)mode);
         }
         PrintRedirectConfigurations.SetWsUrlPriority(converterType, svc.Endpoint.ListenUri.ToString());
         return(res);
     }
     catch (Exception ex)
     {
         logger.Error(ex);
         if (svc != null)
         {
             PrintRedirectConfigurations.SetWsUrlFault(converterType, svc.Endpoint.ListenUri.ToString());
         }
         if (ret >= PrintRedirectConfigurations.GetIstance().ServicesCount)
         {
             throw;
         }
         lastWs = svc.Endpoint.ListenUri.ToString();
         ret   += 1;
         return(Convert(blob, fileExtension, extReq, converterType));
     }
 }
Example #9
0
        public byte[] Convert(byte[] fileSource, string fileExtension, string extReq, AttachConversionMode mode)
        {
            logger.DebugFormat("Convert {0} to {1}", fileExtension, extReq);
            string fileName = Path.GetTempFileName();

            try
            {
                return(RetryingPolicyAction <byte[]>(() => {
                    File.WriteAllBytes(fileName + fileExtension, fileSource);
                    if (localContext == null)
                    {
                        localContext = uno.util.Bootstrap.bootstrap();
                    }

                    unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager();
                    XComponentLoader componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");

                    PropertyValue[] propertyValue = new PropertyValue[2];
                    PropertyValue aProperty = new PropertyValue();
                    aProperty.Name = "Hidden";
                    aProperty.Value = new uno.Any(true);
                    propertyValue[0] = aProperty;

                    propertyValue[1] = new PropertyValue();
                    propertyValue[1].Name = "IsSkipEmptyPages";
                    propertyValue[1].Value = new uno.Any(true);

                    XComponent xComponent = null;
                    bool toConvert = false;
                    string fileConvertedName;
                    try
                    {
                        string fileToConvertName = PathConverter(fileName + fileExtension);
                        fileConvertedName = PathConverter(fileName + "." + extReq);
                        logger.DebugFormat("Url to comvert: {0} - {1}", fileToConvertName, fileConvertedName);
                        xComponent = componentLoader.loadComponentFromURL(
                            fileToConvertName,
                            "_blank",
                            0,
                            propertyValue
                            );
                        if (xComponent == null)
                        {
                            throw new DocumentNotConvertible_Exception();
                        }

                        logger.Debug("Verify if is to process...");
                        if (fileExtension.Contains("doc") && (UseRedirectMethod(xComponent)))
                        {
                            logger.Debug("No conversion to do...");
                            toConvert = true;
                        }
                        else
                        {
                            object xls = null;

                            if (xComponent is XSpreadsheetDocument)
                            {
                                xls = xComponent as XSpreadsheetDocument;
                            }
                            else if (xComponent is XTextDocument)
                            {
                                xls = xComponent as XTextDocument;
                            }

                            if (xls != null)
                            {
                                //Se i nomi degli sheets sono fra quelli non convertibili, usare il converter Office.
                                if (xls is XSpreadsheetDocument)
                                {
                                    var sheetNames = (xls as XSpreadsheetDocument)
                                                     .getSheets()
                                                     .getElementNames()
                                                     .ToArray();

                                    for (int i = 0; i < sheetNames.Length; i++)
                                    {
                                        sheetNames[i] = (sheetNames[i] ?? string.Empty).ToUpper();
                                    }

                                    var namesSet = (ConfigurationManager.AppSettings["RedirectSheetNames"] ?? string.Empty)
                                                   .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                                                   .OrderByDescending(x => x.Length);

                                    var founded = false;

                                    foreach (var set in namesSet)
                                    {
                                        var names = set
                                                    .Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                                        if (names.Length <= sheetNames.Length)
                                        {
                                            founded = true;
                                            foreach (var n in names)
                                            {
                                                if (!sheetNames.Contains(n.ToUpper()))
                                                {
                                                    founded = false;
                                                    break;
                                                }
                                            }

                                            if (founded)
                                            {
                                                logger.Debug("No conversion to do...");
                                                return null;
                                            }
                                        }
                                    }
                                }

                                //var xls = xComponent as XSpreadsheetDocument;
                                var styles = (xls as XStyleFamiliesSupplier).getStyleFamilies();
                                var pageStyles = styles.getByName("PageStyles").Value as XNameContainer;

                                bool scaleToPages = false;

                                var configured = ConfigurationManager.AppSettings["ScaleToPages"];
                                try
                                {
                                    if (!string.IsNullOrEmpty(configured))
                                    {
                                        var dummy = bool.Parse(configured);
                                        scaleToPages = dummy;
                                    }
                                }
                                catch { logger.ErrorFormat("Invalid value for configured parameter \"{0}\". Current value is \"{1}\".", "ScaleToPages", configured); }

                                var configValue = ConfigurationManager.AppSettings["StampaConforme.ForcePortrait"];
                                var forcePortrait = !string.IsNullOrEmpty(configValue) && configValue.Equals("true", StringComparison.InvariantCultureIgnoreCase);
                                logger.Info("StampaConforme.ForcePortrait: " + forcePortrait.ToString());

                                foreach (var nome in pageStyles.getElementNames())
                                {
                                    var props = pageStyles.getByName(nome).Value as XPropertySet;
                                    if (forcePortrait)
                                    {
                                        var isLandscape = (bool)props.getPropertyValue("IsLandscape").Value;
                                        if (isLandscape)
                                        {
                                            var size = props.getPropertyValue("Size").Value as Size;
                                            var w = size.Width;
                                            size.Width = size.Height;
                                            size.Height = w;
                                            props.setPropertyValue("Size", new uno.Any(typeof(Size), size));
                                            props.setPropertyValue("IsLandscape", new uno.Any(false));
                                        }
                                    }

                                    if (scaleToPages && props.getPropertySetInfo().hasPropertyByName("ScaleToPages"))
                                    {
                                        props.setPropertyValue("ScaleToPages", new uno.Any((short)1));
                                    }
                                }
                            }

                            PropertyValue[] saveProps = new PropertyValue[2];
                            saveProps[0] = new PropertyValue();
                            saveProps[0].Name = "FilterName";
                            saveProps[0].Value = new uno.Any("writer_pdf_Export");

                            saveProps[1] = new PropertyValue();
                            saveProps[1].Name = "IsSkipEmptyPages";
                            saveProps[1].Value = new uno.Any(true);
                            logger.Debug("loadComponentFromURL end.");

                            ((XStorable)xComponent).storeToURL(fileConvertedName, saveProps);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        throw;
                    }
                    finally
                    {
                        if (xComponent != null)
                        {
                            xComponent.dispose();
                        }
                    }
                    logger.DebugFormat("Conversione END - ToConvert: {0}", toConvert);
                    if (toConvert)
                    {
                        return null;
                    }
                    else
                    {
                        return File.ReadAllBytes(fileName + "." + extReq);
                    }
                }));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
            finally
            {
                try
                {
                    File.Delete(fileName + fileExtension);
                    File.Delete(fileName + extReq);
                    File.Delete(fileName);
                }
                catch { }
            }
        }
Example #10
0
 /// <summary>
 /// Converte un documento ed applica la label
 /// </summary>
 /// <returns>
 /// Documento convertito e con label
 /// </returns>
 public byte[] ConvertToFormatLabeled(byte[] documentContent, string fileName, string ext, string label, AttachConversionMode mode = AttachConversionMode.Default)
 {
     logger.DebugFormat("ConvertToFormatLabeled {0} ({1}) {2}", fileName, ext, label);
     //Conversione nel formato richiesto
     byte[] res = ToRasterFormat(documentContent, fileName, ext, out bool isEncripted, mode);
     if (!isEncripted)
     {
         return(AddLabelToConvertedDocument(ext, label, null, res, documentContent));
     }
     return(res);
 }
Example #11
0
        /// <summary>
        /// Converte un documento in formato PDF utilizzando i servizi di conversione
        /// </summary>
        /// <returns>
        /// Documento convertito nel formato <paramref name="extReq">ExtReq</paramref>
        /// </returns>
        public byte[] ToRasterFormat(byte[] documentContent, string fileName, string extReq, out bool isEncripted, AttachConversionMode mode = AttachConversionMode.Default)
        {
            try
            {
                isEncripted = false;
                logger.DebugFormat("ToRasterFormat {0} ({1})", fileName, extReq);
                if (extReq.ToLower().Contains("tif"))
                {
                    if (ConfigurationHelper.GetValueOrDefault <bool>("ConvertTiffAsPdf", false))
                    {
                        logger.Debug("TIF request redirect to PDF conversion");
                        extReq = "PDF";
                    }
                    else
                    {
                        throw new FormatException("Conversione non più supportata, utilizzare il formato PDF");
                    }
                }

                string originalFileName = fileName;
                if (!ConfigurationHelper.GetValueOrDefault <bool>("CompliantPrinting.DisableDSW7Compliant", false))
                {
                    if (!originalFileName.ToPath().HasExtension())
                    {
                        originalFileName = PathUtil.UNDEFINEDFILENAME.ToPath().ChangeExtension("." + originalFileName);
                    }
                }

                //Estrazione del documento se firmato
                // CacheVerify: Verifica se il documento è presente in cache
                byte[] cachedDocumentContent = _cacheService.FindDocument(documentContent, extReq);
                if (cachedDocumentContent != null)
                {
                    return(cachedDocumentContent);
                }
                // Converte il documento nel formato richiesto
                var ret = ConvertToPdf(documentContent, extReq, originalFileName, out isEncripted, mode);
                //Put file to cache
                if (!isEncripted)
                {
                    _cacheService.CreateDocument(ret, documentContent, extReq);
                }

                return(ret);
            }
            catch (Exception exp)
            {
                logger.Error(exp);
                throw;
            }
            finally
            {
                logger.Debug("ToRasterFormat End");
            }
        }
Example #12
0
        private byte[] ConvertToPdf(byte[] content, string customStyle, string destination, string origin, out bool isEncrypted, AttachConversionMode attachConversionMode = AttachConversionMode.Default)
        {
            logger.InfoFormat("PrintRedirected.ConvertToPdf: origin = {0}, destination = {1}", origin, destination);
            try
            {
                isEncrypted = false;
                var contentInfo = new ContentInfo(origin, content);
                if (contentInfo.Extension.EqualsIgnoreCase(PathUtil.EXTENSIONPDF) &&
                    !ConfigurationHelper.GetValueOrDefault <bool>("CompliantPrinting.EnableUnethicalReading", false))
                {
                    isEncrypted = contentInfo.ToPdfContent().IsEncrypted;
                }

                var tx = CompliantTransformerFactory.ToA4Size();
                tx.AttachConversionMode = attachConversionMode;
                tx.PdfTransformer.PdfA  = true;
                tx.CustomStyleContent   = customStyle;


                var result = CompliantPrintingHelper.ConvertToPdf(contentInfo, tx);
                logger.InfoFormat("PrintRedirected.ConvertToPdf: result.Length = {0}", result.Content.Length);
                return(result.Content);
            }
            catch (Exception ex)
            {
                logger.Error("PrintRedirected.ConvertToPdf: Si è verificato un errore.", ex);
                throw ex;
            }
        }
Example #13
0
 private byte[] ConvertToPdf(byte[] content, string destination, string origin, out bool isEncrypted, AttachConversionMode attachConversionMode = AttachConversionMode.Default)
 {
     return(ConvertToPdf(content, null, destination, origin, out isEncrypted, attachConversionMode));
 }
Example #14
0
 public byte[] Convert(byte[] fileSource, string fileExtension, string extReq, AttachConversionMode mode)
 {
     try
     {
         using (Document doc = new Document())
             using (MemoryStream ms = new MemoryStream())
                 using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
                 {
                     doc.Open();
                     using (MemoryStream txtStream = new MemoryStream(fileSource))
                         using (TextReader reader = new StreamReader(txtStream))
                         {
                             doc.Add(new Paragraph(reader.ReadToEnd()));
                         }
                     doc.Close();
                     return(ms.ToDeepCopyArray());
                 }
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
         throw;
     }
 }