예제 #1
0
        /// <summary>
        /// 利用itext7生成文字签名
        /// </summary>
        public void ConvertPdf1()
        {
            string sourcePath = $"C:\\test\\source.pdf";
            string targetPath = $"C:\\test\\target.pdf";
            string fontPath   = $"C:\\Windows\\Fonts\\simkai.ttf";

            string signPath1 = @"C:\Users\Administrator\Desktop\a.png";
            string signPath2 = @"C:\Users\Administrator\Desktop\b.png";
            string signPath3 = @"C:\Users\Administrator\Desktop\c.png";
            string signPath4 = @"C:\Users\Administrator\Desktop\d.png";


            //输入PDF
            using (iText.Kernel.Pdf.PdfReader reader = new iText.Kernel.Pdf.PdfReader(sourcePath))
            {
                //输出PDF
                using (iText.Kernel.Pdf.PdfWriter writer = new iText.Kernel.Pdf.PdfWriter(targetPath))
                {
                    //获取PDF对象
                    using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(reader, writer))
                    {
                        //获取Document对象
                        using (iText.Layout.Document document = new iText.Layout.Document(pdfDocument))
                        {
                            //从物理文件加载图片
                            iText.Layout.Element.Image image1 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath1));
                            iText.Layout.Element.Image image2 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath2));
                            iText.Layout.Element.Image image3 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath3));
                            iText.Layout.Element.Image image4 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath4));

                            //将图片绘制到PDF的绝对坐标上,同时缩放图片
                            //坐标与绘制文字的坐标几乎一致,稍微向左,向上一些
                            //缩放的宽度与后面的宽度一致,示例中是200
                            //缩放的高度计算两个签名之间的高度差,例如93-73=20
                            //注意示例采用的签名图片的尺寸是:400px * 150px,应当采取和它差不多的尺寸效果最佳
                            document.Add(image1.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 93, 200));
                            document.Add(image2.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 73, 200));
                            document.Add(image3.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 53, 200));
                            document.Add(image4.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 33, 200));

                            //加载字体
                            iText.Kernel.Font.PdfFont font = iText.Kernel.Font.PdfFontFactory.CreateFont(fontPath, iText.IO.Font.PdfEncodings.IDENTITY_H, true);

                            //添加文本
                            document.Add(new iText.Layout.Element.Paragraph("签名1").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 90, 200));
                            document.Add(new iText.Layout.Element.Paragraph("签名2").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 70, 200));
                            document.Add(new iText.Layout.Element.Paragraph("签名3").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 50, 200));
                            document.Add(new iText.Layout.Element.Paragraph("签名4").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 30, 200));
                        }
                    }
                }
            }
        }
        public new void ExportToPdf(string path, double width = 700, double height = 370)
        {
            // exports spectrum annotation w/o base seq annotation
            string tempPdfPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), "temp.pdf");
            string tempPngPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), "annotation.png");

            base.ExportToPdf(tempPdfPath, width, height);

            // scales for desired DPI
            double dpiScale = MetaDrawSettings.CanvasPdfExportDpi / 96.0;

            // save base seq as PNG
            SequenceDrawingCanvas.Measure(new Size((int)SequenceDrawingCanvas.Width, (int)SequenceDrawingCanvas.Height));
            SequenceDrawingCanvas.Arrange(new Rect(new Size((int)SequenceDrawingCanvas.Width, (int)SequenceDrawingCanvas.Height)));

            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)(dpiScale * SequenceDrawingCanvas.Width), (int)(dpiScale * SequenceDrawingCanvas.Height),
                                                                     MetaDrawSettings.CanvasPdfExportDpi, MetaDrawSettings.CanvasPdfExportDpi, PixelFormats.Pbgra32);

            renderBitmap.Render(SequenceDrawingCanvas);
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

            using (FileStream file = File.Create(tempPngPath))
            {
                encoder.Save(file);
            }

            // adds base seq annotation to pdf
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(tempPdfPath), new PdfWriter(path));

            iText.Layout.Document document = new iText.Layout.Document(pdfDoc);

            ImageData imgData = ImageDataFactory.Create(tempPngPath);

            iText.Layout.Element.Image img = new iText.Layout.Element.Image(imgData);
            img.SetMarginLeft((float)(-1.0 * SequenceDrawingCanvas.Margin.Left) + 10);
            img.SetMarginTop(-30);
            img.ScaleToFit((float)SequenceDrawingCanvas.Width, (float)SequenceDrawingCanvas.Height);

            document.Add(img);

            document.Close();
            pdfDoc.Close();

            // delete temp files
            File.Delete(tempPdfPath);
            File.Delete(tempPngPath);
        }
예제 #3
0
        public FileResult DownloadPdf(string path)
        {
            var mark = new Markdown();

            var file    = System.IO.File.ReadAllText(path);
            var content = MarkDownHelper.Convert(file, "markdown", "html5");

            byte[] res = null;
            using (var stream = new MemoryStream())
            {
                var writer   = new PdfWriter(stream);
                var pdf      = new PdfDocument(writer);
                var document = new iText.Layout.Document(pdf);

                document.Add(new Paragraph(content));

                HtmlConverter.ConvertToPdf(content, writer);

                res = stream.ToArray();
            }

            return(File(res, MediaTypeNames.Application.Pdf, Path.GetFileNameWithoutExtension(path) + ".pdf"));
        }
        private void Flush(Update update, SubscriberRecord subscriberRecord)
        {
            var currentSessionImages = ItemsQueueRepo.GetCurrentSessionImages(subscriberRecord).ToArray();

            if (!currentSessionImages.Any())
            {
                TelegramClient.SendTextMessageAsync(subscriberRecord.ChatId, "چیزی برای تبدیل به پی دی اف وجود ندارد.",
                                                    replyMarkup: Keyboards.FlushMarkup);
                return;
            }

            TelegramClient.SendTextMessageAsync(subscriberRecord.ChatId, $"در حال بارگزاری { currentSessionImages.Length } فایل",
                                                replyMarkup: Keyboards.FlushMarkup);
            var progreessMsgId = TelegramClient.SendTextMessageAsync(subscriberRecord.ChatId, GetProgressString(0, 10)).Result.MessageId;

            var memStream = new MemoryStream();

            using (var pdfWriter = new PdfWriter(memStream))
                using (var pdfDoc = new PdfDocument(pdfWriter))
                    using (var document = new iText.Layout.Document(pdfDoc, new PageSize(0, 0)))
                    {
                        for (var i = 0; i < currentSessionImages.Length; i++)
                        {
                            var currentSessionImage = currentSessionImages[i];

                            switch (currentSessionImage.ItemType)
                            {
                            case ItemRecord.ItemTypes.IMAGE:
                            {
                                var imageStream = new MemoryStream();
                                var result      = TelegramClient
                                                  .GetInfoAndDownloadFileAsync(currentSessionImage.FileId, imageStream).Result;

                                var image = new Image(ImageDataFactory.Create(imageStream.ToArray()));
                                pdfDoc.AddNewPage(new PageSize(image.GetImageWidth(), image.GetImageHeight()));
                                image.SetFixedPosition(pdfDoc.GetNumberOfPages(), 0, 0);
                                document.Add(image);
                            }
                            break;

                            case ItemRecord.ItemTypes.PDF_FILE:
                            {
                                try
                                {
                                    var memoryStream = new MemoryStream();
                                    var result       = TelegramClient.GetInfoAndDownloadFileAsync(currentSessionImage.FileId, memoryStream).Result;

                                    var bytes      = memoryStream.ToArray();
                                    var tempStream = new MemoryStream(bytes);

                                    using (var pdfReader = new PdfReader(tempStream))
                                    {
                                        using (var newPdfDoc = new PdfDocument(pdfReader))
                                        {
                                            newPdfDoc.CopyPagesTo(1,
                                                                  newPdfDoc.GetNumberOfPages(),
                                                                  pdfDoc);
                                        }
                                    }

                                    tempStream.Close();
                                    memoryStream.Close();
                                }
                                catch (Exception exception)
                                {
                                    var baseException = exception.GetBaseException();
                                    Logger.LogError(baseException, "Read Pdf File Failed: {Message} -> {StackTrace}", baseException.Message, baseException.StackTrace);
                                }
                            }
                            break;

                            default:
                                break;
                            }

                            TelegramClient.EditMessageTextAsync(subscriberRecord.ChatId, progreessMsgId,
                                                                GetProgressString(i + 1, currentSessionImages.Length));
                        }
                    }


            var resultEdit = TelegramClient.EditMessageTextAsync(subscriberRecord.ChatId, progreessMsgId, "در حال آپلود فایل...").Result;

            SendPdf(subscriberRecord, memStream);
            memStream.Close();
            ItemsQueueRepo.ClearCurrentSessionImages(subscriberRecord);
        }
예제 #5
0
        private void Print <T>(bool isRaw, List <T> selectedPersons, int rawpagesCount = 0) where T : IPerson
        {
            var filePath = Path.Combine(Constants.WorkingDirectory, typeof(T) == typeof(Rozhodci) ? "vyplatni-listina-rozhodci.pdf" : "vyplatni-listina-ceta.pdf");

            using (var writer = new PdfWriter(filePath))
            {
                using (var pdf = new PdfDocument(writer))
                {
                    var doc = new Document(pdf, PageSize.A4.Rotate());
                    doc.SetMargins(23, 38, 20, 38);
                    var pagesCount = (int)Math.Ceiling((double)selectedPersons.Count / 10);
                    if (pagesCount == 0)
                    {
                        pagesCount = 1;
                    }
                    if (isRaw)
                    {
                        pagesCount = rawpagesCount;
                    }

                    var font = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA, PdfEncodings.CP1250);
                    var bold = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA_BOLD, PdfEncodings.CP1250);

                    var mainHeaderTitle    = _settings.IsClubNameEnabled ? _settings.ClubName : new string('.', 80);
                    var documentMainHeader = new Paragraph($"TJ, Sportovní klub, Atletický oddíl, Atletický klub: {mainHeaderTitle}")
                                             .SetFont(bold).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER);
                    var listinaHeadText = "VÝPLATNÍ LISTINA ODMĚN ";
                    listinaHeadText += typeof(T) == typeof(Rozhodci) ? "ROZHODČÍCH" : "TECHNICKÉ ČETY";
                    var vyplatniListinaHead = new Paragraph(listinaHeadText)
                                              .SetFont(bold).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER).SetMarginTop(-3);
                    var rules = new Paragraph(
                        "Níže podepsaní účastníci soutěže souhlasili s uvedením svých osobních údajů na této výplatní listině (jméno, příjmení, datum narození a adresa).")
                                .SetFont(font).SetFontSize(9).SetTextAlignment(TextAlignment.CENTER).SetMarginTop(-1).SetMarginBottom(1);
                    var evidenceText =
                        new Paragraph(
                            $"Tyto údaje budou součástí evidence {new string('.', 123)} a budou jen pro vnitřní potřebu.")
                        .SetFont(font).SetFontSize(9).SetTextAlignment(TextAlignment.CENTER).SetMarginTop(-1);

                    var aboutcompetition = new Table(UnitValue.CreatePercentArray(new[] { 52.15f, 47.85f })).SetMarginTop(1).UseAllAvailableWidth();
                    aboutcompetition.AddCell(_settings.IsCompetitionNameEnabled
                                                ? AboutCompetitionCell($"Název soutěže: {_settings.CompetitionName}", bold)
                                                : AboutCompetitionCell($"Název soutěže {new string('.', 89)}", bold));

                    if (_settings.IsCompetitionDateEnabled)
                    {
                        if (_settings.CompetitionStartDate.HasValue && _settings.CompetitionEndDate == null)
                        {
                            aboutcompetition.AddCell(
                                AboutCompetitionCell($"Datum konání soutěže: {_settings.CompetitionStartDate.Value:dd.MM.yyyy}", bold));
                        }
                        else if (_settings.CompetitionStartDate.HasValue && _settings.CompetitionEndDate.HasValue)
                        {
                            aboutcompetition.AddCell(AboutCompetitionCell(
                                                         $"Datum konání soutěže: {_settings.CompetitionStartDate.Value:dd.MM.yyyy} - {_settings.CompetitionEndDate.Value:dd.MM.yyyy}",
                                                         bold));
                        }
                        else
                        {
                            aboutcompetition.AddCell(AboutCompetitionCell($"Datum konání soutěže {new string('.', 70)}", bold));
                        }
                    }
                    else
                    {
                        aboutcompetition.AddCell(AboutCompetitionCell($"Datum konání soutěže {new string('.', 70)}", bold));
                    }

                    var aboutcompetition2 = new Table(UnitValue.CreatePercentArray(new[] { 52.15f, 47.85f })).SetMarginTop(3).UseAllAvailableWidth();
                    if (_settings.IsCompetitionTimeEnabled)
                    {
                        if (_settings.CompetitionStartTime.HasValue && _settings.CompetitionEndTime == null)
                        {
                            aboutcompetition2.AddCell(
                                AboutCompetitionCell($"Doba konání soutěže: {_settings.CompetitionStartTime.Value:HH:mm} - ", bold));
                        }
                        else if (_settings.CompetitionStartTime.HasValue && _settings.CompetitionEndTime.HasValue)
                        {
                            aboutcompetition2.AddCell(AboutCompetitionCell(
                                                          $"Doba konání soutěže: {_settings.CompetitionStartTime.Value:HH:mm} - {_settings.CompetitionEndTime.Value:HH:mm}",
                                                          bold));
                        }
                        else
                        {
                            aboutcompetition2.AddCell(AboutCompetitionCell($"Doba konání soutěže {new string('.', 78)}", bold));
                        }
                    }
                    else
                    {
                        aboutcompetition2.AddCell(AboutCompetitionCell($"Doba konání soutěže {new string('.', 78)}", bold));
                    }

                    aboutcompetition2.AddCell(_settings.IsCompetitionPlaceEnabled
                                                ? AboutCompetitionCell($"Místo konání soutěže: {_settings.CompetitionPlace}", bold)
                                                : AboutCompetitionCell($"Místo konání soutěže {new string('.', 72)}", bold));

                    #region TableHead

                    var pdfNumber = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                    .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                    .SetFont(font)
                                    .SetPadding(0)
                                    .SetBorder(new SolidBorder(1));
                    pdfNumber.Add(new Paragraph("Pořadové"));
                    pdfNumber.Add(new Paragraph("číslo"));

                    var nameCell = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                   .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                   .SetFont(font)
                                   .SetHeight(17)
                                   .SetBorder(new SolidBorder(1.2f))
                                   .SetBorderBottom(new GrooveBorder(DeviceCmyk.BLACK, 1, 0.5f))
                                   .SetPadding(0);
                    nameCell.Add(new Paragraph("Jméno a příjmení")).SetPaddingLeft(17);
                    var addressCell = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                      .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                      .SetFont(font)
                                      .SetHeight(17)
                                      .SetBorder(new SolidBorder(1.2f))
                                      .SetBorderTop(Border.NO_BORDER)
                                      .SetPadding(0);
                    addressCell.Add(new Paragraph("Přesná adresa")).SetPaddingLeft(17);

                    var birthDate = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                    .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                    .SetFont(font)
                                    .SetPadding(0);
                    birthDate.Add(new Paragraph("Datum"));
                    birthDate.Add(new Paragraph("narození"));

                    var awardCell = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                    .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                    .SetFont(font)
                                    .SetPadding(0);
                    awardCell.Add(new Paragraph("Odměna"));
                    awardCell.Add(new Paragraph("Kč"));

                    var signCell = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                   .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                   .SetFont(font)
                                   .SetPadding(0);
                    signCell.Add(new Paragraph("Potvrzení o přijetí odměny"));
                    signCell.Add(new Paragraph("Podpis"));

                    #endregion

                    #region Tabulka Bottom

                    var emptyCell = new Cell().SetBorder(Border.NO_BORDER).SetPadding(0f);

                    var sumtextCell = new Cell(1, 2).SetFont(bold).SetFontSize(15).SetTextAlignment(TextAlignment.RIGHT)
                                      .SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetPadding(0);
                    sumtextCell.Add(new Paragraph("CELKEM VYPLACENO: ")).SetPaddingRight(2);

                    var last = new Paragraph(
                        "Vyplatil...............................................     Dne...............................................     Podpis...............................................")
                               .SetFont(font)
                               .SetFontSize(12)
                               .SetMarginTop(8);

                    #endregion

                    for (int i = 0; i < pagesCount; i++)
                    {
                        doc.Add(documentMainHeader);
                        doc.Add(vyplatniListinaHead);
                        doc.Add(rules);
                        doc.Add(evidenceText);
                        doc.Add(aboutcompetition);
                        doc.Add(aboutcompetition2);

                        #region Table

                        var rozhodciTable = new Table(new float[] { 65, 355, 100, 80, 170 })
                                            .UseAllAvailableWidth()
                                            .SetMarginTop(6f)
                                            .SetFontSize(FontSize);

                        rozhodciTable.SetWidth(765f);
                        rozhodciTable.SetBorder(Border.NO_BORDER);
                        rozhodciTable.AddCell(pdfNumber);
                        rozhodciTable.AddCell(nameCell);
                        rozhodciTable.AddCell(birthDate);
                        rozhodciTable.AddCell(awardCell);
                        rozhodciTable.AddCell(signCell);
                        rozhodciTable.AddCell(addressCell);

                        for (int j = 0; j < 10; j++)
                        {
                            var index         = j + i * 10;
                            var pdfNumberData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                                .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                                .SetFont(font)
                                                .SetFontSize(15)
                                                .SetHeight(30)
                                                .SetPadding(0)
                                                .SetBorder(new SolidBorder(1))
                                                .SetBorderLeft(new SolidBorder(1));
                            pdfNumberData.Add(new Paragraph((j + 1).ToString()));

                            var nameCellData = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                               .SetFont(font)
                                               .SetHeight(15)
                                               .SetBorder(new SolidBorder(1.2f))
                                               .SetBorderBottom(new GrooveBorder(DeviceCmyk.BLACK, 1, 0.5f))
                                               .SetPadding(0);

                            var addressCellData = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                                  .SetFont(font)
                                                  .SetHeight(15)
                                                  .SetBorder(new SolidBorder(1.2f))
                                                  .SetBorderTop(Border.NO_BORDER)
                                                  .SetPadding(0);

                            var birthDateData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                                .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                                .SetFont(font)
                                                .SetPadding(0)
                                                .SetHeight(30);

                            var awardCellData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                                .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                                .SetFont(font)
                                                .SetPadding(0)
                                                .SetHeight(30);

                            var signCellData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                               .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                               .SetFont(font)
                                               .SetPadding(0)
                                               .SetHeight(30);
                            signCellData.Add(new Paragraph(""));

                            if (!isRaw && selectedPersons.Count > index)
                            {
                                nameCellData.Add(new Paragraph(selectedPersons[index].FullName)).SetPaddingLeft(17);
                                addressCellData.Add(new Paragraph($"{selectedPersons[index].Address}, {selectedPersons[index].City}"))
                                .SetPaddingLeft(17);
                                birthDateData.Add(new Paragraph(selectedPersons[index].BirthDate.ToShortDateString()));
                                awardCellData.Add(new Paragraph(selectedPersons[index].Reward.HasValue
                                                                        ? selectedPersons[index].Reward.Value.ToString()
                                                                        : ""));
                            }
                            else
                            {
                                nameCellData.Add(new Paragraph("")).SetPaddingLeft(17);
                                addressCellData.Add(new Paragraph("")).SetPaddingLeft(17);
                                birthDateData.Add(new Paragraph(""));
                                awardCellData.Add(new Paragraph(""));
                            }


                            rozhodciTable.AddCell(pdfNumberData);
                            rozhodciTable.AddCell(nameCellData);
                            rozhodciTable.AddCell(birthDateData);
                            rozhodciTable.AddCell(awardCellData);
                            rozhodciTable.AddCell(signCellData);
                            rozhodciTable.AddCell(addressCellData);
                        }

                        #endregion

                        var sumCell = new Cell().SetBackgroundColor(ColorConstants.LIGHT_GRAY)
                                      .SetPadding(0)
                                      .SetFont(bold)
                                      .SetFontSize(15)
                                      .SetTextAlignment(TextAlignment.CENTER)
                                      .SetVerticalAlignment(VerticalAlignment.MIDDLE);
                        sumCell.Add(selectedPersons.Count <= i * 10 + 10
                                                        ? new Paragraph(!isRaw ? CountSum(selectedPersons.GetRange(i * 10, selectedPersons.Count - i * 10)) : "")
                                                        : new Paragraph(!isRaw ? CountSum(selectedPersons.GetRange(i * 10, 10)) : ""));

                        rozhodciTable.AddCell(emptyCell);
                        rozhodciTable.AddCell(sumtextCell);
                        rozhodciTable.AddCell(sumCell);
                        rozhodciTable.AddCell(emptyCell);
                        doc.Add(rozhodciTable);

                        doc.Add(last);
                    }

                    doc.Close();
                }
            }

            Browser.OpenLink(filePath);
        }