public void Merge_ThreeDocuments_ResultHasThreePages() { try { PdfMerger.Merge(MergedFile, @"Resources\A4 Test Page.pdf", @"Resources\A3 Test Page.pdf", @"Resources\B5 Test Page.pdf"); var info = new PdfInfo(MergedFile); Assert.AreEqual(3, info.NumberOfPages); } finally { File.Delete(MergedFile); } }
public void Setup() { info = new PdfInfo(@"Resources\A3 Test Page.pdf"); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; foreach (var visit in info.Educations) { var visitLabel = section.AddParagraph("Курс №" + visit.Id + " от " + visit.DateOfBuying.ToShortDateString()); visitLabel.Style = "NormalTitle"; visitLabel.Format.SpaceBefore = "1cm"; visitLabel.Format.SpaceAfter = "0,25cm"; var doctorsLabel = section.AddParagraph("Лекции:"); doctorsLabel.Style = "NormalTitle"; var doctorTable = document.LastSection.AddTable(); List <string> headerWidths = new List <string> { "1cm", "3cm", "2cm", "3cm", "3cm", "3cm", "2,5cm" }; foreach (var elem in headerWidths) { doctorTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = doctorTable, Texts = new List <string> { "№", "Название", "Спец.", "Время", "Цена", "Количество" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); int i = 1; foreach (var doctor in visit.EducationCourses) { CreateRow(new PdfRowParameters { Table = doctorTable, Texts = new List <string> { i.ToString(), doctor.CourseName, doctor.Specialication, (doctor.Duration * doctor.Count).ToString(), (doctor.Cost * doctor.Count).ToString(), doctor.Count.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } CreateRow(new PdfRowParameters { Table = doctorTable, Texts = new List <string> { "", "", "", "", "", "Итого:", visit.FinalCost.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); if (visit.Status == EducationStatus.Имеется) { CreateRow(new PdfRowParameters { Table = doctorTable, Texts = new List <string> { "", "", "", "", "", "К получению:", visit.FinalCost.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } else { CreateRow(new PdfRowParameters { Table = doctorTable, Texts = new List <string> { "", "", "", "", "", "К получению:", visit.LeftSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } if (info.Payments[visit.Id].Count == 0) { continue; } var paymentsLabel = section.AddParagraph("Получено:"); paymentsLabel.Style = "NormalTitle"; var paymentTable = document.LastSection.AddTable(); headerWidths = new List <string> { "1cm", "3cm", "3cm", "3cm" }; foreach (var elem in headerWidths) { paymentTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { "№", "Дата", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); i = 1; foreach (var payment in info.Payments[visit.Id]) { CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { i.ToString(), payment.DatePayment.ToString(), payment.Sum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
public void ShouldThrowExceptionWhenFileNameIsNull() { Assert.Throws <ArgumentNullException>("fileName", () => PdfInfo.Create((string)null)); }
public void ShouldThrowExceptionWhenFileIsPng() { if (!Ghostscript.IsAvailable) { return; } var exception = Assert.Throws <MagickDelegateErrorException>(() => PdfInfo.Create(Files.CirclePNG)); Assert.Single(exception.RelatedExceptions); Assert.Contains("Error: /syntaxerror in pdfopen", exception.RelatedExceptions.First().Message); }
/* * public void ReadJson(String jsonfile) * { * using (StreamReader r = new StreamReader(jsonfile)) * { * string json = r.ReadToEnd(); * * PdfPassJson = JsonConvert.DeserializeObject<PassJson>(json); * Console.WriteLine(PdfPassJson.EventTicket.HeaderFields[0].Key); * * } * return; * } */ public void Test ( Boolean Debug, String FileName ) { Console.WriteLine("Start"); // Step 1: Create empty document // Arguments: page width: 8.5”, page height: 11”, Unit of measure: inches // Return value: PdfDocument main class Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName); // for encryption test // Document.SetEncryption(null, null, Permission.All & ~Permission.Print, EncryptionType.Aes128); // Debug property // By default it is set to false. Use it for debugging only. // If this flag is set, PDF objects will not be compressed, font and images will be replaced // by text place holder. You can view the file with a text editor but you cannot open it with PDF reader. Document.Debug = Debug; PdfInfo Info = PdfInfo.CreatePdfInfo(Document); Info.Title("TicketPassCard"); Info.Author("blueskaie"); Info.Keywords("PDF, .NET, C#, Library, Document Creator"); Info.Subject("PDF File Writer C# Class Library (Version 1.14.1)"); // Step 2: create resources // define font resources DefineFontResources(); // define tiling pattern resources DefineTilingPatternResource(); // Step 3: Add new page Page = new PdfPage(Document); // Step 4:Add contents to page Contents = new PdfContents(Page); // Step 5: add graphices and text contents to the contents object DrawFrameAndBackgroundWaterMark(); DrawLogImage(); //DrawTime(); DrawStrip(); DrawAuxiliaryFields(); DrawBarcode(); // Step 6: create pdf file Document.CreateFile(); // start default PDF reader and display the file Process Proc = new Process(); Proc.StartInfo = new ProcessStartInfo(FileName); Proc.Start(); Console.WriteLine("end"); Console.ReadLine(); // exit return; }
public bool Put(int id, [FromBody] PdfInfo pdfInfo) { return(_pdfInfoDataAccessLayer.Update(id, pdfInfo)); }
public override Bitmap DecodeStream(Stream s, ResizeSettings settings, string optionalPath) { if (string.IsNullOrEmpty(optionalPath)) { if (s.CanSeek) { //Check the header instead if no filename is present. byte[] header = new byte[4]; s.Read(header, 0, 4); bool isPdf = (header[0] == '%' && header[1] == 'P' && header[2] == 'D' && header[3] == 'F'); s.Seek(-4, SeekOrigin.Current); //Restore position. if (!isPdf) { return(null); } } else { return(null); //It's not seekable, we can't check the header. } } else if (!_supportedExtensions.Contains(Path.GetExtension(optionalPath), StringComparer.OrdinalIgnoreCase)) { // Not a supported format return(null); } // Do not allow decoding if Ghostscript there are issues with performing this decode IIssue[] issues = GetIssues().ToArray(); if (issues.Length > 0) { string message = string.Join(Environment.NewLine, issues.Select(x => x.Summary).ToArray()); throw new InvalidOperationException(message); } // Must write input stream to a temporary file for Ghostscript to process. FileInfo tempInputPathInfo = new FileInfo(Path.GetTempFileName()); try { using (FileStream tempInputStream = tempInputPathInfo.Create()) { StreamExtensions.CopyToStream(s, tempInputStream); } // Get information about the PDF such as page count and media boxes // Although this creates a second trip to Ghostscript engine, it's not possible to generate a rendered image in exact // dimensions requested. Skipping this step will cause a rendered image, of some size, to be resized further. PdfInfo pdfInfo = GetPdfInfo(tempInputPathInfo.FullName); // Extract the requested page number from resize settings, or default to first page int pageNumber = settings.GetValueOrDefault("page", 1); // Try to get the page number from PDF info. If not available, abort. This is caused by // requesting a page that does not exist. PageInfo pageInfo = pdfInfo.Pages.SingleOrDefault(x => x.Number == pageNumber); if (pageInfo == null) { return(null); } // We only support media box (as opposed to clip, bleed, art, etc.) If this is not available, abort. if (pageInfo.MediaBox == null) { return(null); } // Get the output size of the generated bitmap by applying the resize settings and media box. Size outputSize = (pageInfo.Rotate == -90 || pageInfo.Rotate == 90) ? GetOutputSize(settings, pageInfo.MediaBox.Height, pageInfo.MediaBox.Width) : GetOutputSize(settings, pageInfo.MediaBox.Width, pageInfo.MediaBox.Height); // Create default Ghostscript settings and apply the resize settings. GhostscriptSettings ghostscriptSettings = new GhostscriptSettings { GhostscriptArgument.NoPause, GhostscriptArgument.Quiet, GhostscriptArgument.Safer, GhostscriptArgument.Batch, { GhostscriptArgument.OutputDevice, "pngalpha" }, { GhostscriptArgument.MaxBitmap, 24000000 }, { GhostscriptArgument.RenderingThreads, 4 }, { GhostscriptArgument.GridFitTT, 0 }, { GhostscriptArgument.AlignToPixels, 0 }, //Subpixel rendering depends on output device... perhaps testing would help determine if 1 would be better? { GhostscriptArgument.FirstPage, pageNumber }, { GhostscriptArgument.LastPage, pageNumber }, GhostscriptArgument.Printed, GhostscriptArgument.PdfFitPage, GhostscriptArgument.FixedMedia, { GhostscriptArgument.Height, outputSize.Height }, { GhostscriptArgument.Width, outputSize.Width } }; ApplyResizeSettings(settings, ghostscriptSettings); // Have Ghostscript process the input to a PNG file with transparency. // The PNG will be reloaded and further processed by the resizer pipeline. FileInfo tempOutputPathInfo = new FileInfo(Path.GetTempFileName()); try { // Add output file and input file. The input file must be the very last argument. ghostscriptSettings.Add(GhostscriptArgument.OutputFile, tempOutputPathInfo.FullName); ghostscriptSettings.Add(tempInputPathInfo.FullName); _engine.Execute(ghostscriptSettings); // NOTE: Do not dispose of memory stream because it is used as the backing source for the loaded bitmap. MemoryStream memoryStream = new MemoryStream((int)tempOutputPathInfo.Length); using (FileStream fileStream = tempOutputPathInfo.Open(FileMode.Open)) { StreamExtensions.CopyToStream(fileStream, memoryStream); } // Per ImagerResizer plugin example source code: // NOTE: If the Bitmap class is used for decoding, read gdi-bugs.txt and make sure you set b.Tag to new BitmapTag(optionalPath,stream); BitmapTag bitmapTag = new BitmapTag("ghostscript.png", memoryStream); return(new Bitmap(memoryStream) { Tag = bitmapTag }); } //catch(GhostscriptException) //{ // // Conversion failed // return null; //or maybe we should show details? If it's a valid PDF? //} finally { tempOutputPathInfo.Delete(); } } finally { tempInputPathInfo.Delete(); } }
public GenerujPolaWDokumencie(string FileName, SingleFakturaProperty singleFaktura) { IHelperData mHelperData = new HelperData(singleFaktura); IDaneNaglowek mDaneNaglowka = new DaneNaglowek(singleFaktura.Work.Naglowek); PdfDocument = new PdfDocument(PaperType.A4, false, UnitOfMeasure.cm, FileName) { Debug = false }; _arialBold = PdfFont.CreatePdfFont(PdfDocument, ArialFontName, FontStyle.Bold); _arialNormal = PdfFont.CreatePdfFont(PdfDocument, ArialFontName, FontStyle.Regular); var Info = PdfInfo.CreatePdfInfo(PdfDocument); Info.Title("Faktura"); Info.Author("TZ"); Info.Keywords("keyword"); Info.Subject("Temat"); _page = new PdfPage(PdfDocument); PdfContents = new PdfContents(_page); IdFaktury(singleFaktura.Work.Naglowek.NumerFaktury); double lastPosition = 26; CreateTable(mDaneNaglowka.GetNaglowekL(), 1.3, 10, 8, lastPosition, lastPosition - 3, false, ContentAlignment.MiddleLeft); lastPosition = CreateTable(mDaneNaglowka.GetNaglowekR(), 10.3, 16, 8, lastPosition, lastPosition - 1.5, false, ContentAlignment.MiddleLeft); lastPosition = CreateTable(mHelperData.GetSprzeNaby(), 1.3, 30, 8, lastPosition - 1.4, lastPosition - 6.2, true, ContentAlignment.MiddleLeft); var widthRow = _arialNormal.TextWidth(8, mHelperData.NrBankowy()[0].Lewa + mHelperData.NrBankowy()[0].Prawa) + 0.25; lastPosition = CreateTable(mHelperData.NrBankowy(), 1.3, 1.3 + widthRow, 8, lastPosition - 1, lastPosition - 6.2, false, ContentAlignment.MiddleLeft); lastPosition = TabelaDaneFaktura(1.3, lastPosition - 1, lastPosition - 11, 19.7, 9, singleFaktura.GetListDt()); RazemWTym(12.03, lastPosition - 0.018, lastPosition - 11, 9); lastPosition = Summary(12.03, lastPosition - 0.018, lastPosition - 11, 19.7, 9, singleFaktura.GetSum()); widthRow = _arialNormal.TextWidth(8, mHelperData.GetZapDoZap()[1].Lewa + mHelperData.GetZapDoZap()[1].Prawa) + 0.25; CreateTable(mHelperData.GetZapDoZap(), 1.3, 1.3 + widthRow, 8, lastPosition - 1, lastPosition - 10, false, ContentAlignment.MiddleLeft); widthRow = _arialNormal.TextWidth(12, mHelperData.Razem()[0].Lewa + mHelperData.Razem()[0].Prawa); lastPosition = CreateTable(mHelperData.Razem(), 19.7 - widthRow, 19.7, 12, lastPosition - 1, lastPosition - 10, false, ContentAlignment.MiddleRight); widthRow = _arialNormal.TextWidth(8, mHelperData.RazemSlownie().Lewa + mHelperData.RazemSlownie().Prawa); lastPosition = CreateTable(new List <DaneTabela> { mHelperData.RazemSlownie() }, 19.7 - widthRow, 19.7, 8, lastPosition, lastPosition - 10, false, ContentAlignment.MiddleRight); RamkiEnd(1.3, lastPosition - 1.4, lastPosition - 5, 9, 7, DictionaryMain.LabelPodpisWystawiania); RamkiEnd(12, lastPosition - 1.4, lastPosition - 5, 19.7, 7, DictionaryMain.LabelPodpisOdbierania); PdfDocument.CreateFile(); }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pdfInfo'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <object> PostByPdfInfoAsync(this IPdfInfos operations, PdfInfo pdfInfo, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostByPdfInfoWithHttpMessagesAsync(pdfInfo, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='casID'> /// </param> /// <param name='dexFlowDocumentType'> /// </param> /// <param name='cycleName'> /// </param> /// <param name='pdfInfo'> /// </param> public static object PutByCasIDDexFlowDocumentTypeCycleNamePdfInfo(this IPdfInfos operations, string casID, string dexFlowDocumentType, string cycleName, PdfInfo pdfInfo) { return(operations.PutByCasIDDexFlowDocumentTypeCycleNamePdfInfoAsync(casID, dexFlowDocumentType, cycleName, pdfInfo).GetAwaiter().GetResult()); }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pdfInfo'> /// </param> public static object PostByPdfInfo(this IPdfInfos operations, PdfInfo pdfInfo) { return(operations.PostByPdfInfoAsync(pdfInfo).GetAwaiter().GetResult()); }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='casID'> /// </param> /// <param name='dexFlowDocumentType'> /// </param> /// <param name='cycleName'> /// </param> /// <param name='pdfInfo'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <object> PutByCasIDDexFlowDocumentTypeCycleNamePdfInfoAsync(this IPdfInfos operations, string casID, string dexFlowDocumentType, string cycleName, PdfInfo pdfInfo, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PutByCasIDDexFlowDocumentTypeCycleNamePdfInfoWithHttpMessagesAsync(casID, dexFlowDocumentType, cycleName, pdfInfo, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public void ShouldThrowExceptionWhenFileIsPng() { Assert.Throws <MagickDelegateErrorException>(() => PdfInfo.Create(Files.CirclePNG)); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.SpaceAfter = "1cm"; paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; var table = document.LastSection.AddTable(); List <string> columns = new List <string> { "6cm", "6cm", "5cm" }; foreach (var elem in columns) { table.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = table, Texts = new List <string> { "Кондитерское изделие", "Ингредиент", "Количество" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); foreach (var product in info.ProductIngredient) { if (product.ProductName == null) { CreateRow(new PdfRowParameters { Table = table, Texts = new List <string> { string.Empty, product.IngredientName, product.TotalCount.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } else { CreateRow(new PdfRowParameters { Table = table, Texts = new List <string> { product.ProductName, string.Empty, string.Empty }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
public PdfInfo GetPDFByDiplomaID(Diploma_model diploma) { PdfInfo pdfInfo = _db.pdfInfos.FirstOrDefault(s => s.diplomaID == diploma.ID); return(pdfInfo); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; foreach (var reception in info.Receptions) { var receptionLabel = section.AddParagraph("Услуга №" + reception.Id + " от " + reception.DateCreate.ToShortDateString()); receptionLabel.Style = "NormalTitle"; receptionLabel.Format.SpaceBefore = "1cm"; receptionLabel.Format.SpaceAfter = "0,25cm"; var servicesLabel = section.AddParagraph("Услуги:"); servicesLabel.Style = "NormalTitle"; var serviceTable = document.LastSection.AddTable(); List <string> headerWidths = new List <string> { "1cm", "3,5cm", "3cm", "3,5cm" }; foreach (var elem in headerWidths) { serviceTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "№", "Название", "Цена", "Количество" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); int i = 1; foreach (var service in reception.ReceptionServices) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { i.ToString(), service.ServiceName, (service.Price * service.Count).ToString(), service.Count.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "Итого:", reception.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); if (reception.ReceptionStatus == ReceptionStatus.Оформлен) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "К оплате:", reception.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } else { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "К оплате:", reception.LeftSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } if (info.Payments[reception.Id].Count == 0) { continue; } var paymentsLabel = section.AddParagraph("Платежи:"); paymentsLabel.Style = "NormalTitle"; var paymentTable = document.LastSection.AddTable(); headerWidths = new List <string> { "1cm", "6cm", "6cm", "3cm" }; foreach (var elem in headerWidths) { paymentTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { "№", "Дата", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); i = 1; foreach (var payment in info.Payments[reception.Id]) { CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { i.ToString(), payment.DatePayment.ToString(), payment.Sum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
public string AddPDF(PdfInfo pdf) { _db.pdfInfos.Add(pdf); _db.SaveChanges(); return("Save Successfully"); }
public bool Post([FromBody] PdfInfo pdfInfo) { return(_pdfInfoDataAccessLayer.Save(pdfInfo)); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.SpaceAfter = "1cm"; paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; paragraph = section.AddParagraph($"с {info.DateFrom.ToShortDateString()} по { info.DateTo.ToShortDateString()}"); paragraph.Format.SpaceAfter = "1cm"; paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "Normal"; var table = document.LastSection.AddTable(); List <string> columns = new List <string> { "3cm", "2cm", "5.5cm", "2.5cm", "3cm" }; foreach (var elem in columns) { table.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = table, Texts = new List <string> { "Маршрут", "Кол-во", "Затраты", "Время", "Стоимость" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); foreach (var route in info.Routes) { string costs = ""; foreach (var cost in route.CostItems) { costs += $"{cost.Name}: {cost.Sum} \n"; } CreateRow(new PdfRowParameters { Table = table, Texts = new List <string> { route.Name, route.Count.ToString(), costs, route.DateVisit.ToString(), route.Cost.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; foreach (var order in info.Orders) { var orderLabel = section.AddParagraph("Заказ №" + order.Id + " от " + order.OrderDate.ToShortDateString()); orderLabel.Style = "NormalTitle"; orderLabel.Format.SpaceBefore = "1cm"; orderLabel.Format.SpaceAfter = "0,25cm"; var furnitureModelLabel = section.AddParagraph("Мебель:"); furnitureModelLabel.Style = "NormalTitle"; var serviceTable = document.LastSection.AddTable(); List <string> headerWidths = new List <string> { "1cm", "4cm", "3cm", "2,5cm", "3cm", "2,5cm" }; foreach (var elem in headerWidths) { serviceTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "№", "Тип", "Модель", "Цена", "Количество", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); int i = 1; foreach (var position in order.Positions) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { i.ToString(), position.TypeName, position.ModelName, position.Price.ToString(), position.Count.ToString(), (position.Price * position.Count).ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "", "", "Итого:", order.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); if (order.Status == PaymentStatus.Оформлен) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "", "", "К оплате:", order.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } else { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "", "", "К оплате:", order.LeftSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } if (info.Payments[order.Id].Count == 0) { continue; } var paymentsLabel = section.AddParagraph("Платежи:"); paymentsLabel.Style = "NormalTitle"; var paymentTable = document.LastSection.AddTable(); headerWidths = new List <string> { "1cm", "7,5cm", "7,5cm" }; foreach (var elem in headerWidths) { paymentTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { "№", "Дата", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); i = 1; foreach (var payment in info.Payments[order.Id]) { CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { i.ToString(), payment.PaymentDate.ToString(), payment.PaymentAmount.ToString(), }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
public bool Update(int id, PdfInfo pdfInfo) { return(_pdfInfoDataAccessLayer.Update(id, pdfInfo)); }
public void ShouldThrowExceptionWhenFileNameIsEmpty() { Assert.Throws <ArgumentException>("fileName", () => PdfInfo.Create(string.Empty)); }
public bool Save(PdfInfo pdfInfo) { return(_pdfInfoDataAccessLayer.Save(pdfInfo)); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; foreach (var excursion in info.Excursions) { var edLabel = section.AddParagraph("Маршрут №" + excursion.Id + " от " + excursion.ExcursionCreate.ToShortDateString()); edLabel.Style = "NormalTitle"; edLabel.Format.SpaceBefore = "1cm"; edLabel.Format.SpaceAfter = "0,25cm"; var routesLabel = section.AddParagraph("Маршруты:"); routesLabel.Style = "NormalTitle"; var routeTable = document.LastSection.AddTable(); List <string> headerWidths = new List <string> { "1cm", "3cm", "2cm", "3cm", "3cm", "3cm", "2,5cm" }; foreach (var elem in headerWidths) { routeTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = routeTable, Texts = new List <string> { "Маршрут №", "Название маршрута", "Дата начала маршрута", "Цена" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); int i = 1; foreach (var route in excursion.RouteForExcursions) { CreateRow(new PdfRowParameters { Table = routeTable, Texts = new List <string> { i.ToString(), route.RouteName, route.StartRoute.ToString(), route.Cost.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } CreateRow(new PdfRowParameters { Table = routeTable, Texts = new List <string> { "", "", "", "", "", "Итого:", excursion.Cost.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); if (excursion.Status == ExcursionStatus.Принят) { CreateRow(new PdfRowParameters { Table = routeTable, Texts = new List <string> { "", "", "", "", "", "К оплате:", excursion.Remain.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } else { CreateRow(new PdfRowParameters { Table = routeTable, Texts = new List <string> { "", "", "", "", "", "К оплате:", excursion.Remain.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } if (info.Orders[excursion.Id].Count == 0) { continue; } var paysLabel = section.AddParagraph("Платежи:"); paysLabel.Style = "NormalTitle"; var payTable = document.LastSection.AddTable(); headerWidths = new List <string> { "1cm", "3cm", "3cm", "3cm" }; foreach (var elem in headerWidths) { payTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = payTable, Texts = new List <string> { "№", "Дата", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); i = 1; foreach (var pay in info.Orders[excursion.Id]) { CreateRow(new PdfRowParameters { Table = payTable, Texts = new List <string> { i.ToString(), pay.DateCreate.ToString(), pay.Sum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
/// <param name='pdfInfo'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <object> > PostByPdfInfoWithHttpMessagesAsync(PdfInfo pdfInfo, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (pdfInfo == null) { throw new ValidationException(ValidationRules.CannotBeNull, "pdfInfo"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("pdfInfo", pdfInfo); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostByPdfInfo", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "gradadm/pdfinfos").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (pdfInfo != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(pdfInfo, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <object>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }