示例#1
0
        public void Merge(string parentFile, IEnumerable <string> filesToMerge)
        {
            var outputPdfDoc = new Doc();

            if (File.Exists(parentFile))
            {
                outputPdfDoc.Read(parentFile);
            }

            try
            {
                foreach (string file in filesToMerge)
                {
                    var inputPdfDoc = new Doc();
                    inputPdfDoc.Read(file);
                    outputPdfDoc.Append(inputPdfDoc);
                    inputPdfDoc.Clear();
                    inputPdfDoc.Dispose();
                }

                outputPdfDoc.Save(parentFile);
            }
            finally
            {
                outputPdfDoc.Clear();
                outputPdfDoc.Dispose();
            }
        }
示例#2
0
        /// <summary>
        /// Merges PDF Documents
        /// </summary>
        /// <param name="documentsToMergeList">Paths of Docuemnts to Merge</param>
        /// <param name="outputLocation">Output Location</param>
        /// <param name="pageSizeEnum"></param>
        /// <returns>Total Numnber of Pages</returns>
        public int MergeDocuments(List <string> documentsToMergeList, string outputLocation, PdfPageSizeEnum pageSizeEnum)
        {
            try
            {
                using (Doc doc1 = new Doc())
                {
                    //set the page size of the entire document
                    doc1.MediaBox.String = pageSizeEnum.ToString();

                    foreach (var documentToMerge in documentsToMergeList)
                    {
                        Doc doc2 = new Doc();

                        doc2.Read(documentToMerge);
                        doc1.Append(doc2);
                        doc2.Dispose();
                    }

                    doc1.Form.MakeFieldsUnique(Guid.NewGuid().ToString());
                    doc1.Encryption.CanEdit      = false;
                    doc1.Encryption.CanChange    = false;
                    doc1.Encryption.CanFillForms = false;
                    doc1.Save(outputLocation);

                    return(doc1.PageCount);
                }
            }
            catch (Exception e)
            {
                var documents = string.Join(", ", (from l in documentsToMergeList select l));
                //this.Log().Error(string.Format("Error converting the following documents {0} to ouput location {1}", documents, outputLocation), e);
                //Throw the stack trace with it.
                throw;
            }
        }
示例#3
0
        public ActionResult GenerateMultiPdf(string a, string l, string resync)
        {
            var sep     = new[] { '|' };
            var ios     = a.Split(sep, StringSplitOptions.RemoveEmptyEntries);
            var lineNos = l.Split(sep, StringSplitOptions.RemoveEmptyEntries);

            if (ios.Any() && lineNos.Any() && ios.Count().Equals(lineNos.Count()))
            {
                var allDocs = new Doc();

                byte[] pdfs = null;

                for (var i = 0; i < ios.Count(); i++)
                {
                    CreateAndAppendDeliveryAssurancesPdf(Request, ios[i], Convert.ToInt32(lineNos[i]), resync == "1", ref allDocs, ref pdfs);
                }

                allDocs.ClearCachedDecompressedStreams();
                allDocs.Clear();
                allDocs.Dispose();

                if (pdfs != null)
                {
                    Response.AddHeader("Content-Disposition", "inline; filename=DeliveryAssurances.pdf");
                    return(File(pdfs, "application/pdf"));
                }
            }

            return(HttpNotFound());
        }
示例#4
0
        /// <summary>
        /// Applies the first page of the PDF file located at waterMarkImagePdfPath as a watermark
        /// to each page of the PDF file located at inputFilePath
        /// </summary>
        /// <param name="inputFilePath">File path of document to be watermarked</param>
        /// <param name="waterMarkImagePdfPath">File path of watermark template</param>
        public void AddWatermark(string inputFilePath, string waterMarkImagePdfPath)
        {
            var temp = inputFilePath + ".watermark";

            var watermarkImage = this.ConvertSinglePdfPageToJpegImage(waterMarkImagePdfPath, 1);

            using (var doc = new Doc())
            {
                doc.Read(inputFilePath);
                int theCount = doc.PageCount;

                int theID = 0;
                for (int i = 1; i <= theCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Layer      = doc.LayerCount + 1;
                    if (i == 1)
                    {
                        theID = doc.AddImageFile(watermarkImage.FullName, 1);
                    }
                    else
                    {
                        doc.AddImageCopy(theID);
                    }
                }
                doc.Save(temp);
                doc.Clear();
                doc.Dispose();
            }

            File.Delete(inputFilePath);
            File.Move(temp, inputFilePath);
            File.Delete(watermarkImage.FullName);
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                Doc?.Dispose();
            }
        }
示例#6
0
        public int MergeDocuments(List <string> documentsToMergeList, List <string> documentsToCreateAndMergeList, string outputLocation, PdfPageSizeEnum pageSizeEnum)
        {
            try
            {
                using (Doc doc1 = new Doc())
                {
                    //set the page size of the entire document
                    doc1.MediaBox.String = pageSizeEnum.ToString();

                    //Merge existing documents
                    foreach (var documentToMerge in documentsToMergeList)
                    {
                        Doc doc2 = new Doc();

                        doc2.Read(documentToMerge);

                        //add each page of the plan to the doc2. It will add it as A4 size
                        for (int i = 1; i <= doc2.PageCount; i++)
                        {
                            doc1.Page = doc1.AddPage();
                            doc1.AddImageDoc(doc2, i, null);
                            doc1.FrameRect();
                        }

                        doc2.Dispose();
                    }

                    //Create New documents and Merge
                    foreach (var documentToCreateAndMerge in documentsToCreateAndMergeList)
                    {
                        using (Doc doc2 = new Doc())
                        {
                            doc2.FontSize = 40;
                            doc2.AddText(documentToCreateAndMerge);
                            doc1.Append(doc2);
                        }
                    }

                    doc1.Form.MakeFieldsUnique(Guid.NewGuid().ToString());
                    doc1.Encryption.CanEdit      = false;
                    doc1.Encryption.CanChange    = false;
                    doc1.Encryption.CanFillForms = false;
                    doc1.Save(outputLocation);
                    return(doc1.PageCount);
                }
            }
            catch (Exception e)
            {
                var documents = string.Join(", ", (from l in documentsToMergeList select l));
                //this.Log().Error(string.Format("Error converting the following documents {0} to ouput location {1}", documents, outputLocation), e);
                //Throw the stack trace with it.
                throw;
            }
        }
示例#7
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    theDoc.Dispose();
                }

                disposedValue = true;
            }
        }
        public void Control()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["LicenseKey"].ConnectionString;
            XSettings.InstallLicense(connectionString);
            var theDoc = new Doc { FontSize = 96 };

            theDoc.AddText("Control");
            Response.ContentType = "application/pdf";
            theDoc.Save(Response.OutputStream);
            theDoc.Clear();
            theDoc.Dispose();
        }
示例#9
0
        public bool ConvertToImage(string pdfPath, string toSaveImagePath, ILogger logger, bool hideSection, List <RectangleDimesion> rectangles, List <RectangleDimesion> highQualityRectangles = null)
        {
            if (pdfPath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                return(false);
            }
            if (toSaveImagePath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                return(false);
            }

            if (File.Exists(pdfPath))
            {
                var    doc          = new Doc();
                string tempSavePath = hideSection ? Directory.GetParent(toSaveImagePath).FullName + "\\temp.jpg" : toSaveImagePath;

                try
                {
                    doc.Read(pdfPath);
                    doc.PageNumber = 1;
                    doc.Rendering.Save(tempSavePath);
                }
                catch (Exception ex)
                {
                    logger.Error("System Failure! File could not be generated. Message: " + ex.Message + " \n\t " +
                                 ex.StackTrace);
                    return(false);
                }
                finally
                {
                    doc.ClearCachedDecompressedStreams();
                    doc.Clear();
                    doc.Dispose();
                }

                if (hideSection)
                {
                    HideEcgFinding(tempSavePath, toSaveImagePath, logger, rectangles);
                }

                var imageName = _settings.HighImageQuality + Path.GetFileName(toSaveImagePath);

                var directoryToSave  = Directory.GetParent(toSaveImagePath).FullName;
                var highQualityImage = Path.Combine(directoryToSave, imageName);

                ConvertToHighQualityImage(pdfPath, highQualityImage, logger, hideSection, highQualityRectangles);

                return(true);
            }
            return(false);
        }
        public Doc GetMergePdf(string html)
        {
            var arlFormsHTML = html.Split(new List <string> {
                "@jump@"
            }.ToArray(),
                                          StringSplitOptions.RemoveEmptyEntries);
            var pdfAllDocs = new Doc();

            foreach (var item in arlFormsHTML)
            {
                var pdfAppend = new Doc();
                pdfAppend = CreatePDFFromString(item);
                pdfAllDocs.Append(pdfAppend);
                pdfAppend.Dispose();
            }
            return(pdfAllDocs);
        }
示例#11
0
 private static void AppendPdf(Doc finalReport, string sourceDocPath)
 {
     if (!string.IsNullOrEmpty(sourceDocPath))
     {
         var sourceDocPdfDoc = new Doc();
         try
         {
             sourceDocPdfDoc.Read(sourceDocPath);
             finalReport.Append(sourceDocPdfDoc);
         }
         finally
         {
             sourceDocPdfDoc.Clear();
             sourceDocPdfDoc.Dispose();
         }
     }
 }
示例#12
0
        private void MicrosoftOfficeWordToPdfConversion(string originalFileName, string targetFileName)
        {
            var xr = new XReadOptions {
                ReadModule = ReadModuleType.MSOffice
            };

            using (var docPdf = new Doc())
            {
                var doc1 = new Doc();
                doc1.Read(originalFileName, xr);

                docPdf.Append(doc1);
                doc1.Dispose();

                docPdf.Save(targetFileName);
            }
        }
示例#13
0
        /// <summary>
        /// Merges PDF Documents and also creates new documents for the string provided and merges them
        /// </summary>
        /// <param name="documentsToMergeList">Existng documents that need to be merged</param>
        /// <param name="documentsToCreateAndMergeList">List of String Data which need to be added to a new document that is merged</param>
        /// <param name="outputLocation">output location where the nerge file gets saved</param>
        /// <returns></returns>
        public int MergeDocuments(List <string> documentsToMergeList, List <string> documentsToCreateAndMergeList, string outputLocation)
        {
            try
            {
                using (Doc doc1 = new Doc())
                {
                    //Merge existing documents
                    foreach (var documentToMerge in documentsToMergeList)
                    {
                        Doc doc2 = new Doc();

                        doc2.Read(documentToMerge);

                        doc1.Append(doc2);

                        doc2.Dispose();
                    }

                    //Create New documents and Merge
                    foreach (var documentToCreateAndMerge in documentsToCreateAndMergeList)
                    {
                        using (Doc doc2 = new Doc())
                        {
                            doc2.FontSize = 40;
                            doc2.AddText(documentToCreateAndMerge);
                            doc1.Append(doc2);
                        }
                    }

                    doc1.Form.MakeFieldsUnique(Guid.NewGuid().ToString());
                    doc1.Encryption.CanEdit      = false;
                    doc1.Encryption.CanChange    = false;
                    doc1.Encryption.CanFillForms = false;
                    doc1.Save(outputLocation);
                    return(doc1.PageCount);
                }
            }
            catch (Exception e)
            {
                var documents = string.Join(", ", (from l in documentsToMergeList select l));
                //this.Log().Error(string.Format("Error converting the following documents {0} to ouput location {1}", documents, outputLocation), e);
                //Throw the stack trace with it.
                throw;
            }
        }
示例#14
0
        public ActionResult GenerateDryingAgrementPdf(string resync = "true")
        {
            var theDoc = new Doc();

            var pdf = CreateDryingAgreementPdf(Request, resync == "true", ref theDoc);

            theDoc.ClearCachedDecompressedStreams();
            theDoc.Clear();
            theDoc.Dispose();

            if (pdf == null)
            {
                return(HttpNotFound());
            }

            Response.AddHeader("Content-Disposition", "inline; filename=DryingAgreement.pdf");
            return(File(pdf, "application/pdf"));
        }
示例#15
0
        private void CreateAndAppendDeliveryAssurancesPdf(HttpRequestBase request, string id, int lineNumber, bool resync, ref Doc allDocs, ref byte[] pdfOut)
        {
            var theDoc = new Doc();

            CreateDeliveryAssurancePdf(request, id, lineNumber, resync, ref theDoc);

            if (allDocs == null)
            {
                allDocs = new Doc();
            }

            allDocs.Append(theDoc);

            pdfOut = allDocs.GetData();

            theDoc.ClearCachedDecompressedStreams();
            theDoc.Clear();
            theDoc.Dispose();
        }
示例#16
0
        public void SavePdfAsTiffImage(string source, string destinationForTiff)
        {
            Doc theDoc = null;

            try
            {
                theDoc = new Doc();
                theDoc.Read(source);

                // set up the rendering parameters

                theDoc.Rendering.ColorSpace = XRendering.ColorSpaceType.Gray;

                theDoc.Rendering.BitsPerChannel = 8;

                theDoc.Rendering.DotsPerInch = 200;

                var pageCount = theDoc.PageCount;

                for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++)
                {
                    theDoc.PageNumber = pageNumber;

                    theDoc.Rect.String = theDoc.CropBox.String;

                    theDoc.Rendering.SaveAppend = (pageNumber != 1);

                    theDoc.Rendering.SaveCompression = XRendering.Compression.LZW;

                    theDoc.Rendering.Save(destinationForTiff);
                }
            }
            finally
            {
                theDoc.Clear();
                theDoc.Dispose();
            }
        }
示例#17
0
        /// <summary>
        /// Merges the documentsToMergeList into the mergeIntoDocument
        /// </summary>
        /// <param name="documentsToMergeList"></param>
        /// <param name="mergeIntoDocument"></param>
        /// <returns></returns>
        public int MergeDocumentsIntoDocument(List <string> documentsToMergeList, string mergeIntoDocument)
        {
            try
            {
                using (Doc docMerge = new Doc())
                {
                    foreach (var documentToMerge in documentsToMergeList)
                    {
                        Doc doc = new Doc();

                        doc.Read(documentToMerge);
                        docMerge.Append(doc);
                        doc.Dispose();
                    }

                    if (new Files.FileHelper().Exits(mergeIntoDocument))
                    {
                        Doc docMergeInto = new Doc();
                        docMergeInto.Read(mergeIntoDocument);
                    }

                    docMerge.Form.MakeFieldsUnique(Guid.NewGuid().ToString());
                    docMerge.Encryption.CanEdit      = false;
                    docMerge.Encryption.CanChange    = false;
                    docMerge.Encryption.CanFillForms = false;
                    docMerge.Save(mergeIntoDocument);
                    return(docMerge.PageCount);
                }
            }
            catch (Exception e)
            {
                var documents = string.Join(", ", (from l in documentsToMergeList select l));
                //this.Log().Error(string.Format("Error converting the following documents {0} to {1}", documents, mergeIntoDocument), e);
                //Throw the stack trace with it.
                throw;
            }
        }
示例#18
0
        /// <summary>
        /// Merges Document1 into Document 2
        /// </summary>
        /// <param name="document1"></param>
        /// <param name="document2"></param>
        /// <returns></returns>
        public int MergeDocuments(string document1, string document2)
        {
            try
            {
                using (Doc docMerge = new Doc())
                {
                    Doc doc1 = new Doc();
                    doc1.Read(document1);

                    Doc doc2 = new Doc();
                    doc2.Read(document2);

                    docMerge.Append(doc1);
                    docMerge.Append(doc2);

                    doc1.Dispose();
                    doc2.Dispose();
                    docMerge.Form.MakeFieldsUnique(Guid.NewGuid().ToString());


                    docMerge.Encryption.CanEdit      = false;
                    docMerge.Encryption.CanChange    = false;
                    docMerge.Encryption.CanFillForms = false;

                    docMerge.Save(document2);

                    return(docMerge.PageCount);
                }
            }
            catch (Exception e)
            {
                //this.Log().Error(string.Format("Error converting a document to PDF: {0} to  {1}", document1, document2), e);
                //Throw the stack trace with it.
                throw;
            }
        }
示例#19
0
        public ActionResult GeneratePdf(string a, string l, string resync)
        {
            var ioNumber = a;
            int lineNumber;

            if (!string.IsNullOrWhiteSpace(ioNumber) && !string.IsNullOrWhiteSpace(l) && int.TryParse(l, out lineNumber))
            {
                var theDoc = new Doc();

                var pdf = CreateDeliveryAssurancePdf(Request, ioNumber, lineNumber, resync == "true", ref theDoc);

                theDoc.ClearCachedDecompressedStreams();
                theDoc.Clear();
                theDoc.Dispose();

                if (pdf != null)
                {
                    Response.AddHeader("Content-Disposition", "inline; filename=DeliveryAssurance.pdf");
                    return(File(pdf, "application/pdf"));
                }
            }

            return(HttpNotFound());
        }
示例#20
0
        public String gerarRelatorioPDF(string cdaEmpCadastro, string cpfCnpj, string cdaQuestionarioEmpresa, string protocolo, string estado, string categoria, Boolean comentarios, Int32 programaId, Int32 turmaId, Int32 avaliador, Int32 intro, Boolean EnviaEmail, Page page)
        {
            if (avaliador == 0)
            {
                new BllQuestionarioEmpresa().AlterarSomenteFlagLeitura(StringUtils.ToInt(cdaQuestionarioEmpresa), true);
            }

            Session.Timeout      = 13000;
            Server.ScriptTimeout = 13000;

            string caminhoFisicoRelatorios = ConfigurationManager.AppSettings["caminhoFisicoRelatorios"];
            string caminhoPaginaRelatorio  = ConfigurationManager.AppSettings["caminhoPaginaRelatorio"];

            try
            {
                string[] files = Directory.GetFiles(caminhoFisicoRelatorios);
                foreach (string file in files)
                {
                    if (!File.GetCreationTime(file).ToShortDateString().Equals(DateTime.Now.ToShortDateString()))
                    {
                        File.Delete(file);
                    }
                }
            }
            catch { }
            string c = "";

            try
            {
                int chave = 0;
                if (comentarios)
                {
                    chave = 1;
                }

                //if (programaId == 3)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2008"];
                //}
                //else if (programaId == 4)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2009"];
                //}
                //else if (programaId == 7)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorioAutoavaliacao"];
                //}

                Doc theDoc = new Doc();
                theDoc.SetInfo(0, "License", "bc8b5c07da69df2b6c476901f513aa8b89ff6d8ce56a16797802be20da7348078ab9ae58bd6c483b");
                theDoc.HtmlOptions.Timeout = 30000000;


                String link = this.getDominio(page) + caminhoPaginaRelatorio + "?CDA_EMP_CADASTRO=" + cdaEmpCadastro + "&TX_CPF_CNPJ=" + cpfCnpj + "&Chave=" + chave + "&Avaliador=" + avaliador + "&Intro=" + intro + "&CEA_QUESTIONARIO_EMPRESA=" + cdaQuestionarioEmpresa + "&Protocolo=" + protocolo + "&turmaId=" + turmaId + "&programaId=" + programaId;

                if (estado != null)
                {
                    link = link + "&naoMostraComentarioJuiz=1";
                }
                else if (page.Request["naoMostraComentarioJuiz"] != null && page.Request["naoMostraComentarioJuiz"].Equals("1"))
                {
                    link = link + "&naoMostraComentarioJuiz=1";
                }
                int theID = theDoc.AddImageUrl(link, true, 1000, true);
                while (true)
                {
                    theDoc.FrameRect();
                    if (!theDoc.Chainable(theID))
                    {
                        break;
                    }
                    theDoc.Page = theDoc.AddPage();
                    theID       = theDoc.AddImageToChain(theID);
                }

                for (int i = 1; i <= theDoc.PageCount; i++)
                {
                    theDoc.PageNumber = i;
                    theDoc.Flatten();
                }

                String ArquivoNome = protocolo + "_" + DateTime.Now.Ticks + ".pdf";
                String CaminhoPDF  = caminhoFisicoRelatorios + ArquivoNome;

                CaminhoPDF = Server.MapPath(CaminhoPDF);

                theDoc.Save(CaminhoPDF);
                theDoc.HtmlOptions.PageCacheClear();
                theDoc.Clear();

                theDoc.Delete(theID);
                theDoc.Dispose();

                theDoc = null;
                GC.Collect();


                Thread.Sleep(5000);

                if (EnviaEmail)
                {
                    //WebUtils.EnviaEmail(Request.QueryString["EmailContato"], "Relatório de AutoAvaliação", new System.Text.StringBuilder(), CaminhoPDF);
                    return(CaminhoPDF);
                    //ClientScript.RegisterClientScriptBlock(Page.GetType(), "closeWindow", "window.close();", true);
                }
                else
                {
                    //Response.Redirect(getDominio(this.Page) + "/Relatorios/" + ArquivoNome);
                    //return null;
                    return("/Relatorios/" + ArquivoNome);
                }
            }
            catch (Exception ex)
            {
                //Response.Write(ex.ToString());
                throw ex;
            }
            return(null);
        }
示例#21
0
 public void Dispose() => Doc.Dispose();
示例#22
0
        /// <summary>
        /// 按一级目录请求页面,二级和以后的目录全部不生成,书签只能定位到一级目录
        /// </summary>
        /// <param name="docList"></param>
        /// <param name="savePath"></param>
        /// <param name="customerName"></param>
        /// <param name="bookTaskUrl">为a标签包含的链接</param>
        /// <returns></returns>
        public static bool MergePdf4(List <PdfDoc> docList, string savePath, string customerName, string bookTaskUrl)
        {
            if (docList.Count == 0)
            {
                return(false);
            }
            Doc doc = new Doc();

            doc.HtmlOptions.Timeout          = 30 * 1000;
            doc.HtmlOptions.UseScript        = true;
            doc.HtmlOptions.UseNoCache       = true;
            doc.HtmlOptions.PageCacheEnabled = false;
            doc.HtmlOptions.PageCacheClear();
            doc.Rect.Inset(52.0, 100.0);

            try
            {
                Dictionary <int, string> titleDic = new Dictionary <int, string>();
                foreach (PdfDoc pd in docList)
                {
                    if (pd.NodePid == 0)//0为根节点,可能为封面,单独处理
                    {
                        continue;
                    }

                    doc.Page = doc.AddPage();
                    doc.AddBookmark(GetPath(docList, pd).TrimEnd('\\'), pd.Expended);
                    titleDic.Add(doc.PageCount, pd.Name);

                    if (pd.Url == null)
                    {
                        continue;
                    }
                    int num = doc.AddImageUrl(pd.Url);

                    while (true)
                    {
                        if (!doc.Chainable(num))
                        {
                            break;
                        }
                        doc.Page = doc.AddPage();
                        num      = doc.AddImageToChain(num);
                        titleDic.Add(doc.PageCount, pd.Name);
                    }
                }
                #region 添加页眉和页脚

                AddHeader(ref doc, titleDic, customerName, bookTaskUrl);
                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    //压缩输出
                    doc.Flatten();
                }
                #endregion
                if (!savePath.ToLower().EndsWith(".pdf"))
                {
                    savePath += ".pdf";
                }
                doc.Save(savePath);
            }
            catch (Exception ex)
            {
                LogError.ReportErrors(ex.Message);
                return(false);
            }
            finally
            {
                doc.Clear();
                doc.Dispose();
            }

            return(true);
        }
示例#23
0
        //public static  bool PageToPdfByteArray(string url, string path, Encoding encoe)
        //{
        //    byte[] pdfBuf;
        //    bool ret = false;
        //    try
        //    {
        //        GlobalConfig gc = new GlobalConfig();

        //        // set it up using fluent notation
        //        gc.SetMargins(new Margins(0, 0, 0, 0))
        //          .SetDocumentTitle("Test document")
        //          .SetPaperSize(PaperKind.A4);
        //        //... etc

        //        // create converter
        //        IPechkin pechkin = new SynchronizedPechkin(gc);

        //        // subscribe to events
        //        //pechkin.Begin += OnBegin;
        //        //pechkin.Error += OnError;
        //        //pechkin.Warning += OnWarning;
        //        //pechkin.PhaseChanged += OnPhase;
        //        //pechkin.ProgressChanged += OnProgress;
        //        //pechkin.Finished += OnFinished;

        //        // create document configuration object
        //        ObjectConfig oc = new ObjectConfig();

        //        // and set it up using fluent notation too
        //        oc.SetCreateExternalLinks(false)
        //        .SetFallbackEncoding(encoe)
        //        .SetLoadImages(true)
        //        .SetPageUri(url);
        //        //... etc

        //        // convert document
        //        pdfBuf = pechkin.Convert(oc);

        //        FileStream fs = new FileStream(path, FileMode.Create);
        //        fs.Write(pdfBuf, 0, pdfBuf.Length);
        //        fs.Close();
        //        ret = true;
        //    }
        //    catch (Exception ex)
        //    {

        //    }

        //    return ret;
        //}

        /// <summary>
        /// 根据页面url,按节点目录生成pdf和对应书签(空页面不生成)
        /// </summary>
        /// <param name="docList"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static bool MergePdf(List <PdfDoc> docList, string savePath)
        {
            if (docList.Count == 0)
            {
                return(false);
            }
            Doc doc = new Doc();

            doc.HtmlOptions.Timeout   = 30 * 1000;
            doc.HtmlOptions.UseScript = true;
            doc.Rect.Inset(36.0, 72.0);//Rect默认是文档整个页面大小, 这里的Inset表示将Rect左右留出36的空白,上下留出72的空白

            string emptyMarkPath = null;
            bool   emptyMarkExp  = false;

            try
            {
                foreach (PdfDoc pd in docList)
                {
                    if (pd.NodePid != 0) //0为根节点,没有页面
                    {
                        if (string.IsNullOrEmpty(pd.Url))
                        {
                            /**
                             * 有些目录可能没有页面内容,这里则先将目录的bookmark路径保存;
                             * **/
                            emptyMarkPath = GetPath(docList, pd).TrimEnd('\\');
                            emptyMarkExp  = pd.Expended;
                        }
                        else
                        {
                            doc.Page = doc.AddPage();
                            if (emptyMarkPath != null)
                            {
                                doc.AddBookmark(emptyMarkPath, emptyMarkExp); //让空目录指定到其第一个子页面
                                emptyMarkPath = null;                         //添加之后置空
                            }
                            doc.AddBookmark(GetPath(docList, pd).TrimEnd('\\'), pd.Expended);

                            int num = doc.AddImageUrl(pd.Url);
                            while (true)
                            {
                                //doc.FrameRect();//给内容区域添加黑色边框
                                if (!doc.Chainable(num))
                                {
                                    break;
                                }
                                doc.Page = doc.AddPage();
                                num      = doc.AddImageToChain(num);
                            }
                        }
                    }
                }
                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Flatten();
                }
                if (!savePath.ToLower().EndsWith(".pdf"))
                {
                    savePath += ".pdf";
                }
                doc.Save(savePath);
            }
            catch (Exception ex)
            {
                LogError.ReportErrors(ex.Message);
                return(false);
            }
            finally
            {
                doc.Clear();
                doc.Dispose();
            }

            return(true);
        }
示例#24
0
        public void GeneratePdf(string pageurl, string fileSavePath, bool showFooterText = false, string footerText = "", string coverSheetPages = "", string customizedLetter = "", string contentpages = "", string kynFile = "", string bloodLetter = "",
                                string doctorLetter   = "", string corporateFluffLetter = "", bool isPpCustomer        = false, string awvTestResult = "", bool isPcpReport = false, bool generatePcpLetter = false, string scannedDocumentsPdf = "", string eawvPdfReport = "",
                                string focAttestation = "", string attestationForm      = "", bool hasSectionToDisplay = true, string mammogram      = "", string ifobt     = "", string urineMicroalbumin  = "", string participantLetter      = "", string chlamydia = "",
                                string awvBoneMass    = "", string osteoporosis         = "", string quantaFloAbi      = "", string hkyn = "", string mybioCheckAssessment  = "", string memberLetter = "", string greenFormAttestation = "", string dpn               = "")
        {
            var finalReport = new Doc();

            int prePrintedCount = 0;

            var beforFinalReportDoc = new Doc();

            try
            {
                if (coverSheetPages != "")
                {
                    var participantLetterDoc = new Doc();
                    var doctorLetterDoc      = new Doc();
                    var customizedLetterDoc  = new Doc();
                    var contentpagesDoc      = new Doc();
                    var eawvPdfDoc           = new Doc();

                    var memberLetterDoc         = new Doc();
                    var greenFormAttestationDoc = new Doc();
                    try
                    {
                        //Cover Sheet
                        beforFinalReportDoc.Read(coverSheetPages);

                        if (!string.IsNullOrWhiteSpace(greenFormAttestation))
                        {
                            greenFormAttestationDoc.Read(greenFormAttestation);
                            beforFinalReportDoc.Append(greenFormAttestationDoc);
                        }

                        //Member Letter
                        if (!string.IsNullOrEmpty(memberLetter))
                        {
                            memberLetterDoc.Read(memberLetter);
                            beforFinalReportDoc.Append(memberLetterDoc);
                        }

                        if (!string.IsNullOrEmpty(participantLetter))
                        {
                            participantLetterDoc.Read(participantLetter);
                            beforFinalReportDoc.Append(participantLetterDoc);
                        }

                        //Doctor letter
                        if (!string.IsNullOrEmpty(doctorLetter))
                        {
                            doctorLetterDoc.Read(doctorLetter);
                            beforFinalReportDoc.Append(doctorLetterDoc);
                        }
                        //Customized Letter Hospital Partner no default letter
                        if (!string.IsNullOrEmpty(customizedLetter))
                        {
                            customizedLetterDoc.Read(customizedLetter);
                            beforFinalReportDoc.Append(customizedLetterDoc);
                        }

                        if (!string.IsNullOrEmpty(contentpages))
                        {
                            contentpagesDoc.Read(contentpages);
                            beforFinalReportDoc.Append(contentpagesDoc);
                        }

                        if (!string.IsNullOrEmpty(eawvPdfReport))
                        {
                            eawvPdfDoc.Read(eawvPdfReport);
                            beforFinalReportDoc.Append(eawvPdfDoc);
                        }

                        prePrintedCount = beforFinalReportDoc.PageCount;
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        participantLetterDoc.Clear();
                        participantLetterDoc.Dispose();

                        doctorLetterDoc.Clear();
                        doctorLetterDoc.Dispose();

                        customizedLetterDoc.Clear();
                        customizedLetterDoc.Dispose();

                        contentpagesDoc.Clear();
                        contentpagesDoc.Dispose();

                        eawvPdfDoc.Clear();
                        eawvPdfDoc.Dispose();

                        memberLetterDoc.Clear();
                        memberLetterDoc.Dispose();

                        greenFormAttestationDoc.Clear();
                        greenFormAttestationDoc.Dispose();
                    }
                }

                if (hasSectionToDisplay)
                {
                    finalReport.Rect.Inset(40, 70);
                    //pdfDoc.Rect.
                    finalReport.MediaBox.String = PaperSize;
                    finalReport.Rect.String     = finalReport.MediaBox.String;
                    finalReport.Page            = finalReport.AddPage();
                    finalReport.HtmlOptions.PageCachePurge();
                    finalReport.HtmlOptions.Timeout = 90000;


                    if (AllowLoadingJavascriptbeforePdfGenerate)
                    {
                        finalReport.HtmlOptions.UseScript = true;
                    }

                    int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true);

                    while (true)
                    {
                        if (!finalReport.Chainable(imageToChain))
                        {
                            break;
                        }
                        finalReport.Page = finalReport.AddPage();
                        imageToChain     = finalReport.AddImageToChain(imageToChain);
                    }

                    footerText = string.IsNullOrEmpty(footerText) ? string.Empty : footerText + " | ";
                    int pageCount = finalReport.PageCount + prePrintedCount;
                    for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++)
                    {
                        finalReport.PageNumber = pageNumber;
                        if (showFooterText)
                        {
                            int pNum = pageNumber + prePrintedCount;

                            string txt = footerText + "Page: " + pNum + " of " + pageCount;

                            finalReport.Color.String = "0 0 0"; //Dark grey text

                            finalReport.TextStyle.VPos = 0.98;
                            finalReport.TextStyle.HPos = (pageNumber % 2) == 0 ? 0.10 : 0.80;

                            finalReport.AddFont("Arial");
                            //Add the page number
                            finalReport.AddText(txt);


                            //Add a line above page number
                            finalReport.AddLine(21, 40, 590, 40);
                        }

                        //Flatten page
                        finalReport.Flatten();
                    }
                }



                if (!string.IsNullOrEmpty(kynFile))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(kynFile);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                AppendPdf(finalReport, hkyn);

                if (!string.IsNullOrEmpty(bloodLetter))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(bloodLetter);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(corporateFluffLetter))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(corporateFluffLetter);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(awvTestResult))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(awvTestResult);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(scannedDocumentsPdf))
                {
                    var inputScannedPdfDoc = new Doc();
                    try
                    {
                        inputScannedPdfDoc.Read(scannedDocumentsPdf);
                        finalReport.Append(inputScannedPdfDoc);
                    }
                    finally
                    {
                        inputScannedPdfDoc.Clear();
                        inputScannedPdfDoc.Dispose();
                    }
                }

                AppendPdf(finalReport, focAttestation);
                AppendPdf(finalReport, attestationForm);
                AppendPdf(finalReport, mammogram);
                AppendPdf(finalReport, ifobt);
                AppendPdf(finalReport, urineMicroalbumin);
                AppendPdf(finalReport, chlamydia);
                AppendPdf(finalReport, awvBoneMass);
                AppendPdf(finalReport, osteoporosis);
                AppendPdf(finalReport, quantaFloAbi);
                AppendPdf(finalReport, mybioCheckAssessment);
                AppendPdf(finalReport, dpn);

                if (coverSheetPages != "")
                {
                    try
                    {
                        beforFinalReportDoc.Append(finalReport);
                        beforFinalReportDoc.Save(fileSavePath);
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                }
                else
                {
                    finalReport.Save(fileSavePath);
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                finalReport.Clear();
                finalReport.Dispose();

                beforFinalReportDoc.Clear();
                beforFinalReportDoc.Dispose();
            }
        }
示例#25
0
        public void GeneratePdfForHaf(string pageurl, string fileSavePath, string corporateSurveyPdf = "", string basicBiometricFile = "", string focAttestationFile = "", string corporateCheckListPdf = "", string annualComprehensiveExamPdf = "",
                                      string memberInformationProfilePdf = "")
        {
            var finalReport = new Doc();

            try
            {
                finalReport.Rect.Inset(40, 70);
                //pdfDoc.Rect.
                finalReport.MediaBox.String = PaperSize;
                finalReport.Rect.String     = finalReport.MediaBox.String;
                finalReport.Page            = finalReport.AddPage();
                finalReport.HtmlOptions.PageCachePurge();
                finalReport.HtmlOptions.Timeout = 90000;

                if (AllowLoadingJavascriptbeforePdfGenerate)
                {
                    finalReport.HtmlOptions.UseScript = true;
                }

                int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true);

                while (true)
                {
                    if (!finalReport.Chainable(imageToChain))
                    {
                        break;
                    }
                    finalReport.Page = finalReport.AddPage();
                    imageToChain     = finalReport.AddImageToChain(imageToChain);
                }

                for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++)
                {
                    finalReport.PageNumber = pageNumber;
                    //Flatten page
                    finalReport.Flatten();
                }

                if (!string.IsNullOrEmpty(basicBiometricFile))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(basicBiometricFile);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(corporateSurveyPdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(corporateSurveyPdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                if (!string.IsNullOrEmpty(focAttestationFile))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(focAttestationFile);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }
                if (!string.IsNullOrEmpty(corporateCheckListPdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(corporateCheckListPdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }
                if (!string.IsNullOrEmpty(annualComprehensiveExamPdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(annualComprehensiveExamPdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }
                if (!string.IsNullOrEmpty(memberInformationProfilePdf))
                {
                    var inputPdfDoc = new Doc();
                    try
                    {
                        inputPdfDoc.Read(memberInformationProfilePdf);
                        finalReport.Append(inputPdfDoc);
                    }
                    finally
                    {
                        inputPdfDoc.Clear();
                        inputPdfDoc.Dispose();
                    }
                }

                finalReport.Save(fileSavePath);
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                finalReport.Clear();
                finalReport.Dispose();
            }
        }
		private Doc CreateTestDoc(int assessmentID, List<AssessmentPrintBatchHelper> assessmentPrintBatchHelpers, Doc doc, string imagesUrl,bool isAdminInst=false)
        {
            /*  Modified to add uploaded document */
            int userID = SessionObject.LoggedInUser.Page;
            var assessmentInfo = Assessment.GetConfigurationInformation(assessmentID, userID);
            var contentType = assessmentInfo.ContentType;
            bool stringCompareResult = contentType.Equals(_externalTestType, StringComparison.OrdinalIgnoreCase);
            bool noDataFlag = true;

            if (!contentType.Equals(_externalTestType, StringComparison.OrdinalIgnoreCase))    // Is this an External Test
            {
                doc = Assessment.RenderAssessmentToPdf_Batch(assessmentID, assessmentPrintBatchHelpers, imagesUrl, isAdminInst); // Not an External Document
                noDataFlag = false;
            }
            else
            {
                foreach (var assessmentPrintBatchHelper in assessmentPrintBatchHelpers)  //Test Can have multiple Forms (Example: Form 201, Form 101, form 301, etc.)
                {
                    DataTable tbl = Assessment.GetDocs(assessmentID);
                    string tempFile = string.Empty;
                    string AnswerKeyTempFile = tbl.Rows[0][_answerKeyFile].ToString();
                    string[] attachmentTypes = { _assementFile, _reviewerFile, _answerKeyFile };  //rename formNames Attacment types
                   
                    /** Print Uploaded Assessment file **/
                    foreach (string attachmentType in attachmentTypes)
                    {
                        if (!string.IsNullOrEmpty(tbl.Rows[0][attachmentType].ToString()))
                        {
                            tempFile = tbl.Rows[0][attachmentType].ToString();
                            using (Doc externalDoc = new Doc())
                            {
                                int docCount = 0;
                                switch (attachmentType)
                                {
                                    case _assementFile:
                                        docCount = assessmentPrintBatchHelper.AssessmentCount;
                                        break;
                                    case _reviewerFile:
                                        docCount = assessmentPrintBatchHelper.AssessmentCount;
                                        break;
                                    case _answerKeyFile:
                                        docCount = assessmentPrintBatchHelper.AnswerKeyCount;
                                        break;
                                }
                                externalDoc.Read(Server.MapPath("~/upload/" + tempFile));

                                for (int j = 0; j < docCount; j++)
                                {
                                    doc.Append(externalDoc);
                                    noDataFlag = false;
                                }
                            }
                             
                        }                        
                    }


                    //Ashley Reeves said that the Answer Key must Print if there is no enternal file loaded - Reference TFS Bug 1350
                    if (string.IsNullOrEmpty(AnswerKeyTempFile) && assessmentPrintBatchHelper.AnswerKeyCount > 0)
                    {
                        Doc answerKeyDoc = new Doc();
                        answerKeyDoc = Assessment.RenderAssessmentToPdf(assessmentID, assessmentPrintBatchHelper.FormID, PdfRenderSettings.PrintTypes.AnswerKey, isAdminInst);
                        //answerKeyDoc = Assessment.RenderAssessmentAnswerKeyToPdf_Batch(assessmentID, assessmentPrintBatchHelpers); // Not an External Document
                        for (int j = 0; j < assessmentPrintBatchHelper.AnswerKeyCount; j++)
                        {
                            doc.Append(answerKeyDoc);
                            noDataFlag = false;
                        }
                        answerKeyDoc.Dispose();
                    }
                    //1-30-2014 Bug 13579:Print on External Assessment with Rubric should print Rubric and not blank pdf
                    if (assessmentPrintBatchHelper.RubricCount > 0)
                    {
                        Doc RubricDoc = new Doc();
                        RubricDoc = Assessment.RenderAssessmentToPdf(assessmentID, assessmentPrintBatchHelper.FormID, PdfRenderSettings.PrintTypes.Rubric, isAdminInst);
                        for (int j = 0; j < assessmentPrintBatchHelper.RubricCount; j++)
                        {
                            doc.Append(RubricDoc);
                            noDataFlag = false;
                        }
                        RubricDoc.Dispose();
                    }
                    //END 1-30-2014 Bug 13579
                }
                #region JavaScript
                //string scriptName = "MasterJavaScript";
                //string myScriptName = "CustomMessage";
                //if (noDataFlag && !ClientScript.IsClientScriptBlockRegistered(scriptName) && !ClientScript.IsClientScriptBlockRegistered(myScriptName))  //Verify script isn't already registered
                //{

                //    string masterJavaScriptText = string.Empty;
                //    string filePath = Server.MapPath("~/Scripts/master.js");
                //    using (StreamReader MasterJavaScriptFile = new StreamReader(filePath))
                //    {
                //        masterJavaScriptText = MasterJavaScriptFile.ReadToEnd();
                //    }
                //    if (!string.IsNullOrEmpty(masterJavaScriptText))
                //    {
                //        ClientScript.RegisterClientScriptBlock(this.GetType(), scriptName, masterJavaScriptText);

                //        string myScript = "var confirmDialogText = 'There are no external test or answer sheets loaded. Please upload a test and/or answer sheet.';" +
                //                            "\n customDialog({ maximize: true, maxwidth: 300, maxheight: 100, resizable: false, title: 'No Uploaded Documents', content: confirmDialogText, dialog_style: 'confirm' }," +
                //                            "\n [{ title: 'OK', callback: cancelCallbackFunction }, { title: 'Cancel'}]);";

                        

                //        ClientScript.RegisterStartupScript(this.GetType(), myScriptName, myScript,true);
                //    }


                //}
                #endregion //JavaScript
                
                if (noDataFlag) doc = Assessment.NoExternalFiles();  // Prints if there are no external files to print
            }

            

            /** End of adding the uploaded document **/
            return doc;
        }