public ActionResult GeneratePrints(string Ids, int DocTypeId) { if (!string.IsNullOrEmpty(Ids)) { int SiteId = (int)System.Web.HttpContext.Current.Session["SiteId"]; int DivisionId = (int)System.Web.HttpContext.Current.Session["DivisionId"]; var Settings = new PurchaseOrderSettingService(_unitOfWork).GetPurchaseOrderSettingForDocument(DocTypeId, DivisionId, SiteId); try { List <byte[]> PdfStream = new List <byte[]>(); foreach (var item in Ids.Split(',').Select(Int32.Parse)) { DirectReportPrint drp = new DirectReportPrint(); var pd = db.PurchaseOrderAmendmentHeader.Find(item); LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel { DocTypeId = pd.DocTypeId, DocId = pd.PurchaseOrderAmendmentHeaderId, ActivityType = (int)ActivityTypeContants.Print, DocNo = pd.DocNo, DocDate = pd.DocDate, DocStatus = pd.Status, })); byte[] Pdf; if (pd.Status == (int)StatusConstants.Drafted || pd.Status == (int)StatusConstants.Import || pd.Status == (int)StatusConstants.Modified) { //LogAct(item.ToString()); Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint, User.Identity.Name, item); PdfStream.Add(Pdf); } else if (pd.Status == (int)StatusConstants.Submitted || pd.Status == (int)StatusConstants.ModificationSubmitted) { Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint_AfterSubmit, User.Identity.Name, item); PdfStream.Add(Pdf); } else { Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint_AfterApprove, User.Identity.Name, item); PdfStream.Add(Pdf); } } PdfMerger pm = new PdfMerger(); byte[] Merge = pm.MergeFiles(PdfStream); if (Merge != null) { return(File(Merge, "application/pdf")); } } catch (Exception ex) { string message = _exception.HandleException(ex); return(Json(new { success = "Error", data = message }, JsonRequestBehavior.AllowGet)); } return(Json(new { success = "Success" }, JsonRequestBehavior.AllowGet)); } return(Json(new { success = "Error", data = "No Records Selected." }, JsonRequestBehavior.AllowGet)); }
private int merge(PdfMerger merger, List <MergeItem> mergeTreeList, int initialPageCount) { int pageCount = initialPageCount; PdfDocument src = null; foreach (MergeItem mi in mergeTreeList) { if (mi.fileItem.ItemType == FILE) { Form1.updateProgressBar(Form1.ProgressBarValue.isIncrement, 1, 0); mi.pageNumber = pageCount; try { src = new PdfDocument(new PdfReader(mi.fileItem.getFullPath)); if (!(KEEP_IMPORT_BOOKMARKS && !ADD_BOOKMARK_FOR_EACH_FILE)) { destPdfOutlines.AddOutline(FILE_MARKER + mi.fileItem.getName()); } merger.Merge(src, 1, src.GetNumberOfPages()); if (src != null && !src.IsClosed()) { logMsgDbLn2("adding file", ("adding (" + src.GetNumberOfPages() + ") pages").PadRight(20) + ":: " + mi.fileItem.getName()); pageCount += src.GetNumberOfPages(); src.Close(); } else { logMsgln(" added(-no-) pages"); } } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { logMsgFmtln("corrupted PDF found"); if (!CONTINUE_ON_CORRUPT_PDF) { return(-1); } mi.fileItem.ItemType = MISSING; mi.pageNumber = -1; } } if (mi.mergeItems != null) { pageCount = merge(merger, mi.mergeItems, pageCount); if (pageCount < 1) { break; } } } return(pageCount); }
public ActionResult GeneratePrints(string Ids, int DocTypeId) { if (!string.IsNullOrEmpty(Ids)) { int SiteId = (int)System.Web.HttpContext.Current.Session["SiteId"]; int DivisionId = (int)System.Web.HttpContext.Current.Session["DivisionId"]; var Settings = new MaterialPlanLineService(_unitOfWork).GetMaterialPlanSettingsForDocument(DocTypeId, DivisionId, SiteId); if (new RolePermissionService(_unitOfWork).IsActionAllowed(UserRoles, DocTypeId, null, this.ControllerContext.RouteData.Values["controller"].ToString(), "GeneratePrints") == false) { return(View("~/Views/Shared/PermissionDenied.cshtml").Warning("You don't have permission to do this task.")); } try { List <byte[]> PdfStream = new List <byte[]>(); foreach (var item in Ids.Split(',').Select(Int32.Parse)) { DirectReportPrint drp = new DirectReportPrint(); var pd = db.MaterialPlanHeader.Find(item); LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel { DocTypeId = pd.DocTypeId, DocId = pd.MaterialPlanHeaderId, ActivityType = (int)ActivityTypeContants.Print, DocNo = pd.DocNo, DocDate = pd.DocDate, DocStatus = pd.Status, })); byte[] Pdf; if (pd.Status == (int)StatusConstants.Drafted || pd.Status == (int)StatusConstants.Import || pd.Status == (int)StatusConstants.Modified) { //LogAct(item.ToString()); Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint, User.Identity.Name, item); PdfStream.Add(Pdf); } else if (pd.Status == (int)StatusConstants.Submitted || pd.Status == (int)StatusConstants.ModificationSubmitted) { Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint, User.Identity.Name, item); PdfStream.Add(Pdf); } else { Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint, User.Identity.Name, item); PdfStream.Add(Pdf); } } PdfMerger pm = new PdfMerger(); byte[] Merge = pm.MergeFiles(PdfStream); if (Merge != null) { return(File(Merge, "application/pdf")); } } catch (Exception ex) { string message = _exception.HandleException(ex); return(Json(new { success = "Error", data = message }, JsonRequestBehavior.AllowGet)); } return(Json(new { success = "Success" }, JsonRequestBehavior.AllowGet)); } return(Json(new { success = "Error", data = "No Records Selected." }, JsonRequestBehavior.AllowGet)); }
public ActionResult GeneratePrints(string Route, string ActionName, int Id = 0) { string PrintProcedure = ""; if (!string.IsNullOrEmpty(ActionName)) { var Settings = new StockInHandSettingService(_unitOfWork).GetTrailBalanceSetting(User.Identity.Name, Id, Route); string SqlParameterGroupOn; string SqlParameterShowBalance; string SqlParameterProdType; string SqlParameterSiteId = Settings.SiteIds; string DivisionId = Settings.DivisionIds; string SqlParameterFromDate = Settings.FromDate.HasValue ? Settings.FromDate.Value.ToString("dd/MMM/yyyy") : ""; string SqlParameterToDate = Settings.ToDate.HasValue ? Settings.ToDate.Value.ToString("dd/MMM/yyyy") : ""; SqlParameterProdType = Id.ToString(); if (string.IsNullOrEmpty(Settings.GroupOn)) { SqlParameterGroupOn = "NULL"; } else { SqlParameterGroupOn = Settings.GroupOn.ToString(); } if (string.IsNullOrEmpty(Settings.ShowBalance) || Settings.ShowBalance == StockInHandShowBalanceConstants.All) { SqlParameterShowBalance = "NULL"; } else { SqlParameterShowBalance = Settings.ShowBalance.ToString(); } string[] s = Settings.GroupOn.ToString().Split(new Char[] { ',' }); int i = s.Length; string ReportName = "SELECT 'StockInDisplay" + i.ToString() + "'"; //Web.spStockInHand if (ActionName == "StockInHand") { //PrintProcedure = "Web.spStockInHand_ForMultipleProductTest @ProductType ='" + SqlParameterProdType.ToString() + "', @Site='" + SqlParameterSiteId.ToString() + "', @FromDate='" + SqlParameterFromDate.ToString() + "', @ToDate='" + SqlParameterToDate.ToString() + "', @GroupOn='" + SqlParameterGroupOn.ToString() + "', @ShowOpening='" + (Settings.ShowOpening == true ? 1 : 0) + "'"; try { DataTable Dt = new DataTable(); List <byte[]> PdfStream = new List <byte[]>(); DirectReportPrint drp = new DirectReportPrint(); byte[] Pdf; //Pdf = drp.DirectDocumentPrint(PrintProcedure, User.Identity.Name, 0); //drp.DirectPrint(Dt, User.Identity.Name); //PdfStream.Add(Pdf); Pdf = drp.rsDirectDocumentPrintDisplay(ReportName, Route, User.Identity.Name, Id); PdfStream.Add(Pdf); PdfMerger pm = new PdfMerger(); byte[] Merge = pm.MergeFiles(PdfStream); if (Merge != null) { return(File(Merge, "application/pdf")); } } catch (Exception ex) { string message = _exception.HandleException(ex); return(Json(new { success = "Error", data = message }, JsonRequestBehavior.AllowGet)); } } return(Json(new { success = "Success" }, JsonRequestBehavior.AllowGet)); } return(Json(new { success = "Error", data = "No Records Selected." }, JsonRequestBehavior.AllowGet)); }
internal PdfDocument Merge(string outputFile, PdfMergeTree mergeTree) { Form1.configProgressBar(mergeTree.count); listOptions(); if (!VerifyOutputFile(outputFile)) { throw new IOException("Invalid Output File"); } PdfWriter writer = new PdfWriter(outputFile); destPdf = new PdfDocument(writer); destPdfOutlines = destPdf.GetOutlines(false); PdfMerger merger = new PdfMerger(destPdf, MERGE_TAGS, MERGE_BOOKMARKS); merger.SetCloseSourceDocuments(false); logMsgDbLn2(""); int pageCount = merge(merger, mergeTree.GetMergeItems, 1) - 1; logMsgFmtln("total page count", pageCount); if (pageCount < 1) { destPdf.Close(); return(null); } if (KEEP_IMPORT_BOOKMARKS && ADD_BOOKMARK_FOR_EACH_FILE) { // process and adjust bookmarks MergeOutlines(destPdf.GetOutlines(true).GetAllChildren(), mergeTree.GetMergeItems); } if (!(KEEP_IMPORT_BOOKMARKS && !ADD_BOOKMARK_FOR_EACH_FILE)) { // eliminate all of the current bookmarks destPdfOutlines = clearOutline(destPdf); } if (ADD_BOOKMARK_FOR_EACH_FILE) { // add the new bookmarks addOutline(mergeTree.GetMergeItems, destPdfOutlines, 0); } // all complete // leave open for further processing // destPdf.Close(); // return the final PDF document PdfCatalog destPdfCatalog = destPdf.GetCatalog(); destPdfCatalog.SetPageMode(PdfName.UseOutlines); destPdfCatalog.SetPageLayout(PdfName.SinglePage); destPdfCatalog.SetOpenAction(PdfExplicitDestination.CreateFit(1)); return(destPdf); }
public void ExportEmails(string query, string exportPath) { var emailThreads = _googleApiService.GetEmailThreads(query); foreach (var emailThread in emailThreads) { try { var emailThreadDate = emailThread.Emails.Last().DateCreated.ToString("yyyy-MM-dd HH-mm-ss"); var emailThreadSubject = emailThread.Emails.First().Subject.ToValidFileName(); var emailThreadSender = new MailAddress(emailThread.Emails.First().From); var pdfFilename = Path.Combine(exportPath, $"{emailThreadDate} - {emailThreadSender.Address} - {emailThreadSubject}.pdf"); _logger.LogInformation($"Create new pdf, Filename={pdfFilename}"); using (var pdfDocument = new PdfDocument(new PdfWriter(pdfFilename))) { var pdfMerger = new PdfMerger(pdfDocument); foreach (var email in emailThread.Emails) { string emailContent; if (email.Content.Any(x => x.MimeType == "text/html")) { emailContent = email.Content.First(x => x.MimeType == "text/html").Content; } else { emailContent = $"<html><head></head><body><pre>{email.Content.First().Content}</pre></body></html>"; } if (Regex.IsMatch(emailContent, "(<head.*?>)")) { var styleToInject = $@" <style> table.sl-header td {{ font-family: Helvetica; font-size: 14px; }} </style>"; emailContent = Regex.Replace(emailContent, $"(<head.*?>)", $"$1{styleToInject}"); } if (Regex.IsMatch(emailContent, "(<body.*?>)")) { var descriptionToInject = $@" <table class=""sl-header""> <tr> <td width=""100"">Created at</td> <td>{email.DateCreated}</td> </tr> <tr> <td>From</td> <td>{HttpUtility.HtmlEncode(email.From)}</td> </tr> <tr> <td>To</td> <td>{HttpUtility.HtmlEncode(email.To)}</td> </tr> <tr> <td>Subject</td> <td>{email.Subject} </tr> </table> <br/><hr/><br/>"; emailContent = Regex.Replace(emailContent, $"(<body.*?>)", $"$1{descriptionToInject}"); if (false) { emailContent = Regex.Replace(emailContent, @"<style>\s+@media.*?<\/style>", "", RegexOptions.Singleline); } } byte[] byteArray = Encoding.UTF8.GetBytes(emailContent); using (var htmlSource = new MemoryStream(byteArray)) { using (var pdfWriteStream = new MemoryStream()) { var converterProperties = new ConverterProperties(); HtmlConverter.ConvertToPdf(htmlSource, pdfWriteStream, converterProperties); _logger.LogInformation($"Add new pdf page"); var emailPdf = new PdfDocument(new PdfReader(new MemoryStream(pdfWriteStream.ToArray()))); pdfMerger.Merge(emailPdf, 1, emailPdf.GetNumberOfPages()); foreach (var attachment in email.Attachments.Where(x => x.MimeType == "application/pdf")) { _logger.LogInformation($"Add new pdf page"); var attachmentPdf = new PdfDocument(new PdfReader(new MemoryStream(attachment.Data))); pdfMerger.Merge(attachmentPdf, 1, attachmentPdf.GetNumberOfPages()); } } } } } } catch (Exception e) { _logger.LogError(e, "PDF conversion error"); } } }
public string deletePage() { // SaveFiledialog helps with opening a "Save As" window and asking the user for a location and a file name SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "PDF (*.pdf)| *.pdf"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; saveFileDialog1.ShowDialog(); // user selected location is now stored in saveFileDialog1.Filename FileInfo file = new FileInfo(pdfDocument); file.Directory.Create(); PdfDocument pdf = new PdfDocument(new PdfWriter(saveFileDialog1.FileName)); // saves a new pdf filescalled xxxsave.pdf PdfMerger merger = new PdfMerger(pdf); PdfReader reader = new PdfReader(file); PdfWriter writer = pdf.GetWriter(); PdfDocument document = new PdfDocument(reader, writer); int numOfPages = document.GetNumberOfPages(); if (numOfPages == 1) { // The document the user wants to delete from only has 1 page in it. document.Close(); File.Delete(saveFileDialog1.FileName); return("1"); } var PTDList = new List <int>(pagesToDelete); PTDList = PTDList.Distinct().ToList(); if (numOfPages < PTDList.Max()) { // user entered a page number that is larger then the last page of the PDF Documents document.Close(); File.Delete(saveFileDialog1.FileName); return("2"); } if (PTDList.Min() == 0) { // user is trying to delete pages 0, which is impossible document.Close(); File.Delete(saveFileDialog1.FileName); return("3"); } pagesToDelete = PTDList.ToArray(); if (!checkIfOnePage(document.GetNumberOfPages())) { document.RemovePage(pagesToDelete[pagesToDelete.Length - 1]); } else { document.Close(); return("5"); } for (int i = pagesToDelete.Length - 1; i > 0; i--) { if ((i - 1) == 0) { document.RemovePage(pagesToDelete[0]); } else if (!checkIfOnePage(document.GetNumberOfPages())) { document.RemovePage(pagesToDelete[i - 1]); } else { // user document only has 1 page, so we cannot delete any more pages from it document.Close(); return("4"); } } document.Close(); return(saveFileDialog1.FileName); }
//Encargado de juntar todos los documentos PDF generados en uno solo. public void FinalGroup(int Level) { //D:\Portada\HSKBooklets PdfWriter writer = new PdfWriter(@"D:\\HSKBooklet\Final_HSK_" + this.pathLevel + ".pdf"); PdfDocument pdf = new PdfDocument(new PdfWriter(writer)); PdfMerger merger = new PdfMerger(pdf); PdfFont fontKaiti = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED, true); pdf.AddFont(fontKaiti); //Interior Cover //Add pages from the first document PdfDocument InteriorCoverPdf = new PdfDocument(new PdfReader(@"D:\\Portada\HSKBooklets\Interior Cover Level " + this.pathLevel + ".pdf")); //From to merger.Merge(InteriorCoverPdf, 1, InteriorCoverPdf.GetNumberOfPages()); //White White Page A4.pdf PdfDocument IWhitePdf = new PdfDocument(new PdfReader(@"D:\\Portada\HSKBooklets\White Page A4.pdf")); //From to merger.Merge(IWhitePdf, 1, IWhitePdf.GetNumberOfPages()); //HSK Booklets D:\HSKBooklet 1_HSK PdfDocument bookletHSK = new PdfDocument(new PdfReader(@"D:\HSKBooklet\" + this.pathLevel + "_HSK.pdf")); //From to merger.Merge(bookletHSK, 1, bookletHSK.GetNumberOfPages()); //Word Index Cover "Word Index Level 3.pdf" PdfDocument wordIndexCover = new PdfDocument(new PdfReader(@"D:\\Portada\\HSKBooklets\Word Index Level " + this.pathLevel + ".pdf")); //From to merger.Merge(wordIndexCover, 1, wordIndexCover.GetNumberOfPages()); merger.Merge(IWhitePdf, 1, IWhitePdf.GetNumberOfPages()); //Word Index PdfDocument wordIndex = new PdfDocument(new PdfReader(@"D:\\HSKBooklet\" + this.pathLevel + "WordIndex.pdf")); //From to merger.Merge(wordIndex, 1, wordIndex.GetNumberOfPages()); //Char Cover "Character Index Level 1.pdf" PdfDocument CharacterIndexCover = new PdfDocument(new PdfReader(@"D:\\Portada\HSKBooklets\Character Index Level " + this.pathLevel + ".pdf")); //From to merger.Merge(CharacterIndexCover, 1, CharacterIndexCover.GetNumberOfPages()); merger.Merge(IWhitePdf, 1, IWhitePdf.GetNumberOfPages()); //Char Index PdfDocument caracterIndex = new PdfDocument(new PdfReader(@"D:\\HSKBooklet\" + this.pathLevel + "CaracterIndex.pdf")); //From to merger.Merge(caracterIndex, 1, caracterIndex.GetNumberOfPages()); PdfDocument FinalCover = new PdfDocument(new PdfReader(@"D:\Portada\HSKBooklets\End Cover.pdf")); merger.Merge(FinalCover, 1, FinalCover.GetNumberOfPages()); InteriorCoverPdf.Close(); IWhitePdf.Close(); bookletHSK.Close(); wordIndexCover.Close(); InteriorCoverPdf.Close(); wordIndex.Close(); CharacterIndexCover.Close(); caracterIndex.Close(); FinalCover.Close(); pdf.Close(); }
public byte[] GetReport(string Ids, int DocTypeId, string UserName) { int SiteId = (int)System.Web.HttpContext.Current.Session["SiteId"]; int DivisionId = (int)System.Web.HttpContext.Current.Session["DivisionId"]; var Settings = new JobReceiveSettingsService(_unitOfWork).GetJobReceiveSettingsForDocument(DocTypeId, DivisionId, SiteId); string ReportSql = ""; if (!string.IsNullOrEmpty(Settings.DocumentPrint)) { ReportSql = GetReportHeader(Settings.DocumentPrint).ReportSQL; } List <byte[]> PdfStream = new List <byte[]>(); foreach (var item in Ids.Split(',').Select(Int32.Parse)) { DirectReportPrint drp = new DirectReportPrint(); var pd = Find(item); byte[] Pdf; if (!string.IsNullOrEmpty(ReportSql)) { Pdf = drp.rsDirectDocumentPrint(ReportSql, UserName, item); PdfStream.Add(Pdf); } else { if (pd.Status == (int)StatusConstants.Drafted || pd.Status == (int)StatusConstants.Import || pd.Status == (int)StatusConstants.Modified) { Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint, UserName, item); PdfStream.Add(Pdf); } else if (pd.Status == (int)StatusConstants.Submitted || pd.Status == (int)StatusConstants.ModificationSubmitted) { Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint_AfterSubmit, UserName, item); PdfStream.Add(Pdf); } else { Pdf = drp.DirectDocumentPrint(Settings.SqlProcDocumentPrint_AfterApprove, UserName, item); PdfStream.Add(Pdf); } } _logger.LogActivityDetail(logVm.Map(new ActiivtyLogViewModel { DocTypeId = pd.DocTypeId, DocId = pd.JobReceiveHeaderId, ActivityType = (int)ActivityTypeContants.Print, DocNo = pd.DocNo, DocDate = pd.DocDate, DocStatus = pd.Status, })); } PdfMerger pm = new PdfMerger(); byte[] Merge = pm.MergeFiles(PdfStream); return(Merge); }
/// <summary> /// Metoda PdfButton_OnClick(object sender, RoutedEventArgs e) podczas wywolania generuje liste obecnosci dla wybranych pracownikow w postaci plikow PDF /// </summary> /// <param name="sender">Argument typu object, ktory przekazuje obiekt</param> /// <param name="e">Argument typu RoutedEventArgs, ktory przekazuje wszystkie informacje o zdarzeniu </param> private void PdfButton_OnClick(object sender, RoutedEventArgs e) { string fieldShift = "shift_"; // name form for accesing fields in pdf form string fieldStart = "start_"; // startShift form for accesing fields in pdf form string fieldStop = "stop_"; // stopShift form for accesing fields in pdf form int selectedMonth = (int)ListOfMonths.SelectedValue; int selectedYear = (int)ListOfYears.SelectedValue; string strPath = System.AppDomain.CurrentDomain.BaseDirectory; string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string src = $@"{strPath}pdfForm.pdf"; string destMerg = $@"{docPath}\pdfOutput\ListaScalona_{new DateTime(2000, selectedMonth, 1).ToString("MMMMMMMMMMM", CultureInfo.CurrentCulture)}.pdf"; string deletePath = $@"{docPath}\pdfOutput\temp"; DirectoryInfo di = Directory.CreateDirectory($@"{docPath}\pdfOutput\"); if (this.selectedWorkers != null) { PdfDocument mergedPdf = new PdfDocument(new PdfWriter(destMerg)); PdfMerger merger = new PdfMerger(mergedPdf); foreach (var worker in selectedWorkers) { var workerName = worker.Name; string monthName; List <Schedule> schedules; List <Shift> shifts; List <Holiday> holidays; if (ListOfMonths.SelectedValue != null) { monthName = new DateTime(2000, selectedMonth, 1).ToString("MMMMMMMMMMM", CultureInfo.CurrentCulture); } else { InfoOK info = new InfoOK("Nie wybrano pracowników!"); info.ShowDialog(); return; } using (SQLiteConnection connection = new SQLiteConnection(App.databasePath)) { connection.CreateTable <Schedule>(); //read all schedules in selected month/year for specific worker schedules = new List <Schedule> (connection.Table <Schedule>().ToList().Where(c => (c.Date.Month == selectedMonth) && (c.Date.Year == selectedYear) && (c.WorkerId == worker.Id))); connection.CreateTable <Holiday>(); //read all holidays in selected month/year for specific worker holidays = new List <Holiday> (connection.Table <Holiday>().ToList().Where(c => (c.Date.Month == selectedMonth) && (c.Date.Year == selectedYear) && (c.WorkerId == worker.Id))); connection.CreateTable <Shift>(); shifts = new List <Shift> //shifts list (connection.Table <Shift>().ToList().OrderBy(c => c.Id).ToList()); } Directory.CreateDirectory($@"{ docPath}\pdfOutput\temp"); string dest = $@"{docPath}\pdfOutput\temp\{workerName.Replace(" ", "")}.pdf"; // outputPath + generate the workerName pdf PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true); IDictionary <String, PdfFormField> fields = form.GetFormFields(); PdfFormField toSet; fields.TryGetValue("name", out toSet); toSet.SetValue($"{workerName}"); fields.TryGetValue("month", out toSet); toSet.SetValue($"{monthName}"); for (int day = 1; day <= DateTime.DaysInMonth(selectedYear, selectedMonth); day++) { Schedule daySchedule; if (holidays.Where(c => c.Date.Day == day).Count() >= 1) { fields.TryGetValue(fieldShift + day.ToString(), out toSet); if (holidays.Where(c => c.Date.Day == day).First().Type == "Chorobowe") { toSet.SetValue($"N1"); } else { toSet.SetValue($"N2"); } continue; } if (schedules.Where(c => c.Date.Day == day).Count() == 0) { continue; } daySchedule = schedules.Where(c => c.Date.Day == day).First(); if (daySchedule != null) { Shift selectedShift = shifts.Where(c => (c.ShiftName == daySchedule.ShiftName)).ToList().First(); fields.TryGetValue(fieldShift + day.ToString(), out toSet); toSet.SetValue($"{daySchedule.ShiftName}"); fields.TryGetValue(fieldStart + day.ToString(), out toSet); toSet.SetValue($"{selectedShift.TimeFrom.ToString("H:mm")}"); fields.TryGetValue(fieldStop + day.ToString(), out toSet); toSet.SetValue($"{selectedShift.TimeTo.ToString("H:mm")}"); } } pdf.Close(); PdfDocument pdfForMerge = new PdfDocument(new PdfReader(dest)); merger.Merge(pdfForMerge, 1, pdfForMerge.GetNumberOfPages()); pdfForMerge.Close(); } mergedPdf.Close(); Directory.Delete(deletePath, true); InfoOK success = new InfoOK("Utworzono pliki PDF"); success.ShowDialog(); } else { InfoOK info = new InfoOK("Nie wybrano pracowników!"); info.ShowDialog(); } }
private async Task MergePDFs(MainViewModel viewModel) { viewModel.BuildStatus = "Merging PDFs..."; viewModel.BuildProgress = 0; bool overwriteFile = false; //Check if desired output file already exists if (File.Exists(Path.Combine(viewModel.WorkingDirectory, viewModel.OutputName + ".pdf"))) { //ask user to overwrite file var result = MessageBox.Show("File exists, overwrite?", "Overwrite existing file", MessageBoxButton.OKCancel); if (result == MessageBoxResult.Cancel) { return; } else { overwriteFile = true; } } //Copy of real file list to manipulate List <FileObject> tempFileList = CopyFileObjectList(viewModel.Files); //create a temp directory to work in string outputPath = Path.Combine(viewModel.WorkingDirectory, "PDFTemp", viewModel.OutputName + ".pdf"); Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); //copy all files to work in a temp directory. CopyTempFiles(viewModel, tempFileList, outputPath); PdfDocument pdf = null; PdfMerger merger = null; PdfDocument doc = null; try { //check user option for encryption if (viewModel.Encrypt) { pdf = new PdfDocument(new PdfWriter(outputPath, new WriterProperties() .SetStandardEncryption( Encoding.ASCII.GetBytes(viewModel.PDFPass), null, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA) )); } else { pdf = new PdfDocument(new PdfWriter(outputPath)); } merger = new PdfMerger(pdf); foreach (var file in tempFileList) { if (!File.Exists(file.FilePath)) { viewModel.BuildStatus = $"Failed: Temporary file({file.FileName}) no longer exists."; pdf.Close(); merger.Close(); File.Delete(outputPath); return; } try { //check if file is protected if (file.PasswordProtected) { var readerProps = new ReaderProperties(); readerProps.SetPassword(Encoding.ASCII.GetBytes(file.Password)); var pdfReader = new PdfReader(file.FilePath, readerProps); pdfReader.SetUnethicalReading(true); doc = new PdfDocument(pdfReader); } else { var pdfReader = new PdfReader(file.FilePath); doc = new PdfDocument(pdfReader); } } catch (iText.Kernel.PdfException e) { } //merge document var numPages = doc.GetNumberOfPages(); merger.Merge(doc, 1, numPages); doc.Close(); //update build progress viewModel.BuildProgress += numPages; } pdf.Close(); //move to orig location File.Move(outputPath, Path.Combine(viewModel.WorkingDirectory, viewModel.OutputName + ".pdf"), overwriteFile); //delete temp files foreach (var file in tempFileList) { File.Delete(file.FilePath); } //delete temp dir Directory.Delete(Path.GetDirectoryName(outputPath)); viewModel.BuildStatus = "Success: PDF Successfully Created"; } //CLEAN UP THIS EXCEPTION GARBAGE EVENTUALLY catch (iText.IO.IOException e) { viewModel.BuildStatus = "Failed: Corrupt PDF"; } //catch(iText.Signatures.) catch (iText.Kernel.PdfException e) { viewModel.BuildStatus = "Failed: Corrupt PDF"; } catch (FileNotFoundException e) { viewModel.BuildStatus = "Failed: A PDF in the list no longer exists"; } catch (IOException e) { viewModel.BuildStatus = "Failed: Attempting to modify a file in use"; } }
public void Merge_NoSourceDocuments_ThrowsException() { PdfMerger.Merge(MergedFile); }
public void CreateHTML(Dictionary <SignUp, List <ReportSlot> > SignUpData, string FolderPath, bool SeparateFile, DateTime RequestedDate, string FileName) { string FilePath = FileName; List <string> AllPages = new List <string>(); foreach (var roster in SignUpData) { Dispatcher.Invoke((Action)(() => StatusUpdates.Content = string.Format("Creating PDF for {0}", roster.Key.Title))); // Bin slots into times Dictionary <DateTime, List <ReportSlot> > binnedSlots = new Dictionary <DateTime, List <ReportSlot> >(); foreach (var slot in roster.Value) { if (binnedSlots.ContainsKey(slot.StartTime)) { binnedSlots[slot.StartTime].Add(slot); } else { List <ReportSlot> newList = new List <ReportSlot>(); newList.Add(slot); binnedSlots.Add(slot.StartTime, newList); } } // Sort binned slots by time binnedSlots = binnedSlots.OrderBy(training => training.Key).ToDictionary(training => training.Key, training => training.Value); StringWriter stringWriter = new StringWriter(); using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter)) { writer.WriteLine("<!DOCTYPE html>"); writer.WriteLine("<html lang=\"en\">"); writer.RenderBeginTag(HtmlTextWriterTag.Head); writer.WriteLine(); writer.WriteLine("<meta charset=\"utf-8\" />"); writer.RenderBeginTag(HtmlTextWriterTag.Title); writer.Write("Roster for WSTPC Training Sign Ups"); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet"); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css"); writer.AddAttribute(HtmlTextWriterAttribute.Href, "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"); writer.RenderBeginTag(HtmlTextWriterTag.Link); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Style); writer.WriteLine("tr,h5,h3{font-family:Helvetica;}"); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Body); writer.RenderBeginTag(HtmlTextWriterTag.H3); writer.Write(roster.Key.Title + " Training Roster - " + roster.Value[0].StartTime.ToString("M/dd/yyyy")); writer.RenderEndTag(); // Begin Tables foreach (var trainingGroup in binnedSlots) { writer.AddAttribute(HtmlTextWriterAttribute.Class, "noPageBreak"); writer.AddStyleAttribute("page-break-inside", "avoid"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.RenderBeginTag(HtmlTextWriterTag.H5); writer.Write(trainingGroup.Key.ToString("h:mm tt") + " - " + trainingGroup.Value[0].SlotName); writer.RenderEndTag(); // Begin actual tables writer.AddAttribute(HtmlTextWriterAttribute.Class, "table table-bordered"); writer.AddStyleAttribute("font-size", "11pt"); writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag(HtmlTextWriterTag.Thead); writer.RenderBeginTag(HtmlTextWriterTag.Tr); // Header Rows writer.WriteLine("<th scope=\"col\">First Name</th>"); writer.WriteLine("<th scope=\"col\">Last Name</th>"); writer.WriteLine("<th scope=\"col\">Email</th>"); if (trainingGroup.Value[0].CustomQuestions != null) { for (int i = 0; i < trainingGroup.Value[0].CustomQuestions.Count; i++) { writer.WriteLine("<th scope=\"col\"></th>"); } } writer.WriteLine("<th scope=\"col\">Initial</th>"); writer.RenderEndTag(); writer.RenderEndTag(); // List Signup slots writer.RenderBeginTag(HtmlTextWriterTag.Tbody); foreach (var slot in trainingGroup.Value) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(slot.FirstName); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(slot.LastName); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(slot.Email); writer.RenderEndTag(); // Custom Questions if (slot.CustomQuestions != null) { for (int i = 0; i < slot.CustomQuestions.Count; i++) { writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(slot.CustomQuestions[i].Value); writer.RenderEndTag(); } } writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.RenderEndTag(); writer.RenderEndTag(); } writer.RenderEndTag(); // </tbody> writer.RenderEndTag(); // </table> writer.RenderEndTag(); } writer.RenderEndTag(); writer.WriteLine("</html>"); } string tempFilePath = FolderPath + "\\" + roster.Key.Title + " " + RequestedDate.ToString("M-dd-yyyy") + ".pdf"; PdfDocument PDF = new PdfDocument(new PdfWriter(tempFilePath)); ConverterProperties converterProperties = new ConverterProperties(); HtmlConverter.ConvertToPdf(stringWriter.ToString(), PDF, converterProperties); AllPages.Add(tempFilePath); } Dispatcher.Invoke((Action)(() => StatusUpdates.Content = "Combining rosters and opening PDF")); try { PdfDocument MergedPDF = new PdfDocument(new PdfWriter(FilePath)); PdfMerger merger = new PdfMerger(MergedPDF); foreach (var PDFFilePath in AllPages) { PdfDocument PDF = new PdfDocument(new PdfReader(PDFFilePath)); merger.Merge(PDF, 1, PDF.GetNumberOfPages()); PDF.Close(); if (!SeparateFile) { File.Delete(PDFFilePath); } else { System.Diagnostics.Process.Start(PDFFilePath); } } MergedPDF.Close(); System.Diagnostics.Process.Start(FilePath); } catch (Exception e) { MessageBox.Show(e.Message, "Error Saving File", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Append source files after a specific page number to the end of original file. /// </summary> /// <param name="sourceFiles">The list of source files</param> /// <param name="originalFile">Original file to append source files to the end of it</param> /// <param name="pageNumber">Specific page number to append source files after it</param> public void AppendPage(string[] sourceFiles, string originalFile, int pageNumber) { PdfDocument pdfOriginal = null; PdfDocument pdfTemp = null; PdfMerger pdfMerger = null; try { pdfOriginal = new PdfDocument(new PdfReader(originalFile)); // Step 1: Temporary file to prevent rewrite on the original file. // Destination file will be changed with the original in the last step. // In case if the destination file in an existing file pdfTemp = new PdfDocument(new PdfWriter(originalFile + "temp")); pdfMerger = new PdfMerger(pdfTemp); // Step 2: First add the original file content from first page until pageNumber input parameter. pdfMerger.Merge(pdfOriginal, 1, pageNumber); // Step 3: Then add the other source file content for (var i = 0; i < sourceFiles.Length; i++) { using (var pdfSourceFile = new PdfDocument(new PdfReader(sourceFiles[i]))) { pdfMerger.Merge(pdfSourceFile, 1, pdfSourceFile.GetNumberOfPages()); // Update merge job progress. OnUpdateProgress?.Invoke(i); } } // Step 4: Finally append the rest content from Original file, // From the pageNumber to end of the file, if the pageNumber is not the end page. if (pageNumber < pdfOriginal.GetNumberOfPages()) { pdfMerger.Merge(pdfOriginal, pageNumber + 1, pdfOriginal.GetNumberOfPages()); } pdfTemp.Close(); pdfOriginal.Close(); pdfMerger.Close(); // Step 5: Replace the original file with the temp one. File.Delete(originalFile); File.Move(originalFile + "temp", originalFile); } catch (Exception e) { if (pdfTemp != null && !pdfTemp.IsClosed()) { pdfTemp.AddNewPage(); pdfTemp.Close(); pdfOriginal.Close(); pdfMerger?.Close(); } File.Delete(originalFile + "temp"); throw new Exception(e.Message); } }