public virtual void ImageCheckTest2()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer             = new PdfWriter(new MemoryStream());
         Stream @is                   = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                            , @is);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
         doc.AddNewPage();
         PdfCanvas canvas = new PdfCanvas(doc.GetLastPage());
         canvas.AddImage(ImageDataFactory.Create(sourceFolder + "jpeg2000/file5.jp2"), 300, 300, false);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.TypeOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.EXACTLY_ONE_COLOUR_SPACE_SPECIFICATION_SHALL_HAVE_THE_VALUE_0X01_IN_THE_APPROX_FIELD));
     ;
 }
 public virtual void ImageCheckTest3()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer             = new PdfWriter(new MemoryStream());
         Stream @is                   = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                            , @is);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
         doc.AddNewPage();
         PdfCanvas canvas = new PdfCanvas(doc.GetLastPage());
         canvas.AddImage(ImageDataFactory.Create(sourceFolder + "jpeg2000/file7.jp2"), 300, 300, false);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.TypeOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.ExactlyOneColourSpaceSpecificationShallHaveTheValue0x01InTheApproxField));
     ;
 }
 public virtual void ImageCheckTest1()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer             = new PdfWriter(new MemoryStream());
         Stream @is                   = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                            , @is);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
         doc.AddNewPage();
         PdfCanvas canvas = new PdfCanvas(doc.GetLastPage());
         canvas.AddImage(ImageDataFactory.Create(sourceFolder + "jpeg2000/p0_01.j2k"), 300, 300, false);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.TypeOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.ONLY_JPX_BASELINE_SET_OF_FEATURES_SHALL_BE_USED));
     ;
 }
 public virtual void ImageTransparencyTest()
 {
     NUnit.Framework.Assert.That(() => {
         PdfDocument pdfDoc = new PdfADocument(new PdfWriter(new MemoryStream()), PdfAConformanceLevel.PDF_A_3B, null
                                               );
         PdfPage page     = pdfDoc.AddNewPage();
         PdfCanvas canvas = new PdfCanvas(page);
         page.GetResources().SetDefaultRgb(new PdfCieBasedCs.CalRgb(new float[] { 0.3f, 0.4f, 0.5f }));
         canvas.SaveState();
         canvas.AddImage(ImageDataFactory.Create(sourceFolder + "itext.png"), 0, 0, page.GetPageSize().GetWidth() /
                         2, false);
         canvas.RestoreState();
         pdfDoc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfAConformanceException.THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE)))
     ;
 }
示例#5
0
        public void CreateWatermark()
        {
            var tranState = new PdfExtGState();

            tranState.SetFillOpacity(Opacity);

            var reader = new PdfReader(PdfFileName);
            var writer = new PdfWriter(OutFile);
            var pdf    = new PdfDocument(reader, writer);

            var document = new Document(pdf);


            for (int i = 1; i <= pdf.GetNumberOfPages(); i++)
            {
                var page = pdf.GetPage(i);
                page.SetIgnorePageRotationForContent(false);
                var canvas = new PdfCanvas(pdf.GetPage(i));
                canvas.SaveState();
                canvas.SetExtGState(tranState);

                if (ImageFileName != null)
                {
                    var img = ImageDataFactory.Create(ImageFileName);
                    img.SetWidth(ImageWidth);
                    img.SetHeight(ImageHeight);
                    canvas.AddImage(img, AlignX, AlignY, false);
                }

                if (WatermarkText != null)
                {
                    var verticalWatermark = new Paragraph(WatermarkText).SetFontSize(FontSize);
                    document.ShowTextAligned(verticalWatermark, AlignX, AlignY, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM, RadAngle);
                }


                canvas.RestoreState();
            }
            WatermarkText = null;
            ImageFileName = null;
            pdf.Close();
            document.Close();
        }
示例#6
0
 public virtual void Png_imageTransparancy_8bitDepthImage() {
     String outFileName = destinationFolder + "png_imageTransparancy_8bitDepthImage.pdf";
     String cmpFileName = sourceFolder + "cmp_png_imageTransparancy_8bitDepthImage.pdf";
     PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties().SetCompressionLevel
         (CompressionConstants.NO_COMPRESSION)));
     PdfPage page = pdfDocument.AddNewPage(PageSize.A4);
     PdfCanvas canvas = new PdfCanvas(page);
     canvas.SetFillColor(ColorConstants.LIGHT_GRAY).Fill();
     canvas.Rectangle(80, 0, PageSize.A4.GetWidth() - 80, PageSize.A4.GetHeight()).Fill();
     canvas.SaveState().BeginText().MoveText(116, 800).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
         ), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("8 bit depth PNG").MoveText(0, -20).ShowText("This image should not have a black rectangle as background"
         ).EndText().RestoreState();
     ImageData img = ImageDataFactory.Create(sourceFolder + "manualTransparency_8bit.png");
     canvas.AddImage(img, 100, 450, 200, false);
     canvas.Release();
     pdfDocument.Close();
     NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
         , "diff_"));
 }
示例#7
0
        public virtual void InlineImagesTest01()
        {
            String      filename = "inlineImages01.pdf";
            PdfDocument document = new PdfDocument(new PdfWriter(destinationFolder + filename));
            PdfPage     page     = document.AddNewPage();
            PdfCanvas   canvas   = new PdfCanvas(page);

            canvas.AddImage(ImageDataFactory.Create(sourceFolder + "Desert.jpg"), 36, 700, 100, true);
            canvas.AddImage(ImageDataFactory.Create(sourceFolder + "bulb.gif"), 36, 600, 100, true);
            canvas.AddImage(ImageDataFactory.Create(sourceFolder + "smpl.bmp"), 36, 500, 100, true);
            canvas.AddImage(ImageDataFactory.Create(sourceFolder + "itext.png"), 36, 460, 100, true);
            canvas.AddImage(ImageDataFactory.Create(sourceFolder + "0047478.jpg"), 36, 300, 100, true);
            canvas.AddImage(ImageDataFactory.Create(sourceFolder + "map.jp2"), 36, 200, 100, true);
            canvas.AddImage(ImageDataFactory.Create(sourceFolder + "amb.jb2"), 36, 30, 100, true);
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + filename, sourceFolder
                                                                             + "cmp_" + filename, destinationFolder));
        }
示例#8
0
        public virtual void InlineImagesTest02()
        {
            String                filename = "inlineImages02.pdf";
            PdfDocument           document = new PdfDocument(new PdfWriter(destinationFolder + filename));
            PdfPage               page     = document.AddNewPage();
            PdfCanvas             canvas   = new PdfCanvas(page);
            Stream                stream   = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "Desert.jpg"));
            ByteArrayOutputStream baos     = new ByteArrayOutputStream();

            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 700, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "bulb.gif"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 600, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "smpl.bmp"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 500, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "itext.png"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 460, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "0047478.jpg"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 300, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "map.jp2"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 200, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "amb.jb2"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 30, 100, true);
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + filename, sourceFolder
                                                                             + "cmp_" + filename, destinationFolder));
        }
示例#9
0
        public void PdfStamp(string fileout, string stamp, string filein)
        {
            if (File.Exists(filein) && File.Exists(stamp))
            {
                PdfDocument pdf = new PdfDocument(new PdfReader(filein), new PdfWriter(fileout));
                // MessageBox.Show(pdf.GetNumberOfPages().ToString());
                for (var i = 0; i < pdf.GetNumberOfPages(); i++)
                {
                    PdfCanvas canvas = new PdfCanvas(pdf.GetPage(i + 1));
                    ImageData image  = ImageDataFactory.Create(stamp);
                    image.SetRotation(rotation);
                    canvas.SaveState();
                    PdfExtGState state = new PdfExtGState();

                    state.SetFillOpacity(transprency > 1f ? (transprency / 100) : transprency);
                    canvas.SetExtGState(state);


                    System.Drawing.Point newPt =/* new System.Drawing.Point(0, 0);*/
                                                 UCS.shiftAnchor(UCS.Type.pdf, UCS.Corner.TopLeft, anchor,
                                                                 (int)pdf.GetPage(i + 1).GetPageSize().GetWidth(), (int)pdf.GetPage(i + 1).GetPageSize().GetHeight(),

                                                                 (int)image.GetWidth(), (int)image.GetHeight(),

                                                                 new System.Drawing.Point(x, y)
                                                                 );


                    //TODO: add width & height to image
                    canvas.AddImage(image, newPt.X, newPt.Y, false);

                    canvas.RestoreState();
                }
                pdf.Close();
            }
        }
示例#10
0
        public void AddWaterprint(string absoluteFilePath, string outputPath)
        {
            var watermarkImgPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DefaultResource", "waterMarkImg.jpeg");

            using (var pdfDocument = new PdfDocument(new PdfReader(absoluteFilePath), new PdfWriter(outputPath)))
            {
                // image watermark
                ImageData img = ImageDataFactory.Create(watermarkImgPath);

                // transparency
                var gs1 = new PdfExtGState();
                gs1.SetFillOpacity(0.3f);
                for (var pageIndex = 1; pageIndex < pdfDocument.GetNumberOfPages(); pageIndex++)
                {
                    // properties
                    PdfCanvas over     = new PdfCanvas(pdfDocument.GetPage(pageIndex));
                    Rectangle pagesize = pdfDocument.GetPage(pageIndex).GetPageSize();
                    over.SaveState();
                    over.SetExtGState(gs1);
                    over.AddImage(img, 80, 0, 0, 81, 300, (pagesize.GetTop() + pagesize.GetBottom()) - 200, true);
                    over.RestoreState();
                }
            }
        }
        /// <summary>Constructs appearance (top-level) for a signature.</summary>
        /// <remarks>
        /// Constructs appearance (top-level) for a signature.
        /// <p>
        /// Consult <A HREF="http://partners.adobe.com/asn/developer/pdfs/tn/PPKAppearances.pdf">PPKAppearances.pdf</A>
        /// for further details.
        /// </remarks>
        /// <returns>a top-level signature appearance</returns>
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual PdfFormXObject GetAppearance()
        {
            PdfCanvas canvas;

            if (IsInvisible())
            {
                PdfFormXObject appearance = new PdfFormXObject(new Rectangle(0, 0));
                appearance.MakeIndirect(document);
                return(appearance);
            }
            if (n0 == null && !reuseAppearance)
            {
                CreateBlankN0();
            }
            if (n2 == null)
            {
                n2 = new PdfFormXObject(rect);
                n2.MakeIndirect(document);
                String text;
                if (layer2Text == null)
                {
                    StringBuilder buf = new StringBuilder();
                    buf.Append("Digitally signed by ");
                    String name = null;
                    CertificateInfo.X500Name x500name = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate);
                    if (x500name != null)
                    {
                        name = x500name.GetField("CN");
                        if (name == null)
                        {
                            name = x500name.GetField("E");
                        }
                    }
                    if (name == null)
                    {
                        name = "";
                    }
                    buf.Append(name).Append('\n');
                    buf.Append("Date: ").Append(SignUtils.DateToString(signDate));
                    if (reason != null)
                    {
                        buf.Append('\n').Append(reasonCaption).Append(reason);
                    }
                    if (location != null)
                    {
                        buf.Append('\n').Append(locationCaption).Append(location);
                    }
                    text = buf.ToString();
                }
                else
                {
                    text = layer2Text;
                }
                if (image != null)
                {
                    if (imageScale == 0)
                    {
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, rect.GetWidth(), 0, 0, rect.GetHeight(), 0, 0);
                    }
                    else
                    {
                        float usableScale = imageScale;
                        if (imageScale < 0)
                        {
                            usableScale = Math.Min(rect.GetWidth() / image.GetWidth(), rect.GetHeight() / image.GetHeight());
                        }
                        float w = image.GetWidth() * usableScale;
                        float h = image.GetHeight() * usableScale;
                        float x = (rect.GetWidth() - w) / 2;
                        float y = (rect.GetHeight() - h) / 2;
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, w, 0, 0, h, x, y);
                    }
                }
                PdfFont font;
                if (layer2Font == null)
                {
                    font = PdfFontFactory.CreateFont();
                }
                else
                {
                    font = layer2Font;
                }
                float     size          = layer2FontSize;
                Rectangle dataRect      = null;
                Rectangle signatureRect = null;
                if (renderingMode == PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION || renderingMode == PdfSignatureAppearance.RenderingMode
                    .GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null)
                {
                    if (rect.GetHeight() > rect.GetWidth())
                    {
                        signatureRect = new Rectangle(MARGIN, rect.GetHeight() / 2, rect.GetWidth() - 2 * MARGIN, rect.GetHeight()
                                                      / 2);
                        dataRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() / 2 - 2 * MARGIN);
                    }
                    else
                    {
                        // origin is the bottom-left
                        signatureRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() / 2 - 2 * MARGIN, rect.GetHeight() - 2 * MARGIN
                                                      );
                        dataRect = new Rectangle(rect.GetWidth() / 2 + MARGIN / 2, MARGIN, rect.GetWidth() / 2 - MARGIN, rect.GetHeight
                                                     () - 2 * MARGIN);
                    }
                }
                else
                {
                    if (renderingMode == PdfSignatureAppearance.RenderingMode.GRAPHIC)
                    {
                        if (signatureGraphic == null)
                        {
                            throw new InvalidOperationException();
                        }
                        /*MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only")*/
                        signatureRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() - 2 * MARGIN);
                    }
                    else
                    {
                        // take all space available
                        dataRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() * (1 - TOP_SECTION
                                                                                                                   ) - 2 * MARGIN);
                    }
                }
                switch (renderingMode)
                {
                case PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION: {
                    String signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("CN");
                    if (signedBy == null)
                    {
                        signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("E");
                    }
                    if (signedBy == null)
                    {
                        signedBy = "";
                    }
                    canvas = new PdfCanvas(n2, document);
                    Paragraph paragraph = new Paragraph(signedBy).SetFont(font).SetFontSize(layer2FontSize).SetMargin(0).SetMultipliedLeading
                                              (0.9f);
                    new iText.Layout.Canvas(canvas, document, signatureRect).Add(paragraph);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION: {
                    if (signatureGraphic == null)
                    {
                        throw new InvalidOperationException();
                    }
                    /*MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description")*/
                    float imgWidth = signatureGraphic.GetWidth();
                    if (imgWidth == 0)
                    {
                        imgWidth = signatureRect.GetWidth();
                    }
                    float imgHeight = signatureGraphic.GetHeight();
                    if (imgHeight == 0)
                    {
                        imgHeight = signatureRect.GetHeight();
                    }
                    float multiplierH = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier  = Math.Min(multiplierH, multiplierW);
                    imgWidth  *= multiplier;
                    imgHeight *= multiplier;
                    float x = signatureRect.GetRight() - imgWidth;
                    float y = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth, 0, 0, imgHeight, x, y);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC: {
                    float imgWidth_1 = signatureGraphic.GetWidth();
                    if (imgWidth_1 == 0)
                    {
                        imgWidth_1 = signatureRect.GetWidth();
                    }
                    float imgHeight_1 = signatureGraphic.GetHeight();
                    if (imgHeight_1 == 0)
                    {
                        imgHeight_1 = signatureRect.GetHeight();
                    }
                    float multiplierH_1 = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW_1 = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier_1  = Math.Min(multiplierH_1, multiplierW_1);
                    imgWidth_1  *= multiplier_1;
                    imgHeight_1 *= multiplier_1;
                    float x_1 = signatureRect.GetLeft() + (signatureRect.GetWidth() - imgWidth_1) / 2;
                    float y_1 = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight_1) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth_1, 0, 0, imgHeight_1, x_1, y_1);
                    break;
                }
                }
                if (renderingMode != PdfSignatureAppearance.RenderingMode.GRAPHIC)
                {
                    canvas = new PdfCanvas(n2, document);
                    Paragraph paragraph_1 = new Paragraph(text).SetFont(font).SetFontSize(layer2FontSize).SetMargin(0).SetMultipliedLeading
                                                (0.9f);
                    new iText.Layout.Canvas(canvas, document, dataRect).Add(paragraph_1);
                }
            }
            int       rotation = document.GetPage(page).GetRotation();
            Rectangle rotated  = new Rectangle(rect);

            if (topLayer == null)
            {
                topLayer = new PdfFormXObject(rotated);
                topLayer.MakeIndirect(document);
                float scale = Math.Min(rect.GetWidth(), rect.GetHeight()) * 0.9f;
                float x     = (rect.GetWidth() - scale) / 2;
                float y     = (rect.GetHeight() - scale) / 2;
                scale /= 100;
                canvas = new PdfCanvas(topLayer, document);
                if (rotation == 90)
                {
                    canvas.ConcatMatrix(0, 1, -1, 0, rect.GetHeight(), 0);
                }
                else
                {
                    if (rotation == 180)
                    {
                        canvas.ConcatMatrix(-1, 0, 0, -1, rect.GetWidth(), rect.GetHeight());
                    }
                    else
                    {
                        if (rotation == 270)
                        {
                            canvas.ConcatMatrix(0, -1, 1, 0, 0, rect.GetWidth());
                        }
                    }
                }
                if (reuseAppearance)
                {
                    PdfAcroForm    acroForm = PdfAcroForm.GetAcroForm(document, true);
                    PdfFormField   field    = acroForm.GetField(fieldName);
                    PdfStream      stream   = field.GetWidgets()[0].GetAppearanceDictionary().GetAsStream(PdfName.N);
                    PdfFormXObject xobj     = new PdfFormXObject(stream);
                    if (stream != null)
                    {
                        topLayer.GetResources().AddForm(xobj, new PdfName("n0"));
                        PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                        canvas1.AddXObject(xobj, 1, 0, 0, 1, 0, 0);
                    }
                    else
                    {
                        reuseAppearance = false;
                        if (n0 == null)
                        {
                            CreateBlankN0();
                        }
                    }
                }
                if (!reuseAppearance)
                {
                    topLayer.GetResources().AddForm(n0, new PdfName("n0"));
                    PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                    canvas1.AddXObject(n0, 1, 0, 0, 1, 0, 0);
                }
                topLayer.GetResources().AddForm(n2, new PdfName("n2"));
                PdfCanvas canvas1_1 = new PdfCanvas(topLayer, document);
                canvas1_1.AddXObject(n2, 1, 0, 0, 1, 0, 0);
            }
            PdfFormXObject napp = new PdfFormXObject(rotated);

            napp.MakeIndirect(document);
            napp.GetResources().AddForm(topLayer, new PdfName("FRM"));
            canvas = new PdfCanvas(napp, document);
            canvas.AddXObject(topLayer, 0, 0);
            return(napp);
        }
示例#12
0
        private void createClicked(object sender, EventArgs e)
        {
            //Figure out the file name
            startDate = dateTimePicker1.Value;
            endDate   = startDate.AddDays(7);

            destFileName  = destPath.Text + "/";
            destFileName += startDate.ToString("yyyy MMMM d");
            destFileName += " - ";
            if (endDate.Year != startDate.Year)
            {
                destFileName += endDate.ToString("yyyy") + " ";
            }
            if (endDate.Month != startDate.Month)
            {
                destFileName += endDate.ToString("MMMM") + " ";
            }
            destFileName += endDate.Day;
            destFileName += " Murlis";
            destFileName += ".pdf";

            createButton.Text = "Creating...";
            createButton.Refresh();

            //Create the pdf
            writer = new PdfWriter(destFileName);
            pdf    = new PdfDocument(writer);
            //Loop through each day
            for (int i = 0; i < 14; i += 2)
            {
                //Reset togetherHeight
                togetherHeight = 0;
                //Crop the images
                for (int j = 0; j < 2; j++)
                {
                    //Rectangle for part of image we want
                    cropRectangle = new System.Drawing.Rectangle(croppedImageX, croppedImageYs[i + j], croppedImageWidth, croppedImageHeights[i + j]);
                    //Get bitmap from already gotten image
                    croppedImage = new Bitmap(images[i + j]);
                    //Crop the image
                    croppedImage = croppedImage.Clone(cropRectangle, croppedImage.PixelFormat);
                    //Add the height onto the togetherHeight
                    togetherHeight += croppedImage.Height;
                    //Convert to ImageData
                    imageDatas[i + j] = ImageDataFactory.Create((byte[])imageConverter.ConvertTo(croppedImage, typeof(byte[])));
                }
                //Add a  page and canvas to the pdf
                page   = pdf.AddNewPage(PageSize.A4.Rotate());
                canvas = new PdfCanvas(page);
                //Calculate ratios
                pageImageWidthRatio  = page.GetPageSize().GetWidth() / croppedImage.Width;
                pageImageHeightRatio = page.GetPageSize().GetHeight() / togetherHeight;
                smallerRatio         = Math.Min(pageImageWidthRatio, pageImageHeightRatio);
                bottomSpace          = page.GetPageSize().GetHeight() - togetherHeight * smallerRatio;
                //Set transform
                canvas.ConcatMatrix(AffineTransform.GetScaleInstance(smallerRatio, smallerRatio));
                //Add the images onto the canvas
                canvas.AddImage(imageDatas[i], 0, imageDatas[i + 1].GetHeight() + bottomSpace, true);
                canvas.AddImage(imageDatas[i + 1], 0, bottomSpace, true);
            }
            //Save the pdf
            pdf.Close();

            openButton.Enabled  = true;
            closeButton.Enabled = true;
            MessageBox.Show("PDF Successfully Created");
            createButton.Text = "Create";
        }
示例#13
0
        public MemoryStream GeneratePDF(Diploma_model diploma)
        {
            /*byte[] bytes = new byte[diploma.Name.Length * sizeof(char)];
             * System.Buffer.BlockCopy(diploma.Name.ToArray(), 0, bytes, 0, bytes.Length);
             * Encoding w1250 = Encoding.GetEncoding(1250);
             * Encoding utf8 = Encoding.GetEncoding("utf-8");
             * byte[] output = Encoding.Convert(utf8, w1250, utf8.GetBytes(diploma.Name));
             * diploma.Name = w1250.GetString(output);
             *
             * byte[] bytes1 = new byte[diploma.LastName.Length * sizeof(char)];
             * System.Buffer.BlockCopy(diploma.LastName.ToArray(), 0, bytes, 0, bytes.Length);
             * Encoding w12501 = Encoding.GetEncoding(1250);
             * Encoding utf81 = Encoding.GetEncoding("utf-8");
             * byte[] output1 = Encoding.Convert(utf81, w12501, utf81.GetBytes(diploma.LastName));
             * diploma.LastName = w1250.GetString(output1);*/

            using (MemoryStream stream = new MemoryStream())
                using (var writer = new PdfWriter(stream))
                {
                    //var writer = new PdfWriter(stream);
                    var pdf = new PdfDocument(writer);
                    //Fonts
                    PdfFont times_new_roman      = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN, iText.IO.Font.PdfEncodings.CP1257, true);
                    PdfFont times_new_roman_bold = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD, iText.IO.Font.PdfEncodings.CP1257, true);
                    //Text Generic
                    Text rector         = new Text($"{diploma.RectorsName} {diploma.RectorsLastName} \nRektorius \nRector").SetFont(times_new_roman);
                    Text dateofissueLT  = new Text($"Išdavimo data:           {diploma.DateOfIssue.ToString("yyyy/MM/dd")}").SetFont(times_new_roman);
                    Text dateofissueENG = new Text($"Date of issue:          {diploma.DateOfIssue.ToString("dd/MMMM/yyyy")}").SetFont(times_new_roman);
                    //Text LT (fix it later)
                    Text namepart                  = new Text($"{diploma.Name.ToUpper()} {diploma.LastName.ToUpper()} ").SetFont(times_new_roman_bold);
                    Text identitypart              = new Text($"(asmens kodas {diploma.IdentityNumber})").SetFont(times_new_roman);
                    Text partBeforeprogramme       = new Text($"{diploma.DateOfIssue.Year} metais baigė bakalauro studijų programą ").SetFont(times_new_roman);
                    Text programmepart             = new Text($"{diploma.StudiesProgramme.ToUpper()} ").SetFont(times_new_roman_bold);
                    Text programmerGovermentIDCode = new Text($"(valstybinis kodas {diploma.StudiesProgrammeGovermentCode} )").SetFont(times_new_roman);
                    Text beforedegreepart          = new Text("ir jam suteiktas").SetFont(times_new_roman);
                    Text degreepart                = new Text($"{diploma.Degree.ToUpper()} ").SetFont(times_new_roman_bold);
                    Text afterdegreepart           = new Text("laipsnis").SetFont(times_new_roman);
                    Text studiesdirectionpart      = new Text($"Studijų kryptis - {diploma.Studiesdirection.ToUpper()}").SetFont(times_new_roman);
                    //Text Eng
                    Text identitypartENG = new Text($" (personal number/code {diploma.IdentityNumber})").SetFont(times_new_roman);
                    //Text degreeENG = new Text($"BACHELORS DEGREE OF {diploma.Degree.ToUpper()} ").SetFont(times_new_roman);
                    //Text studiesdirectionENG = new Text($"IN {diploma.Studiesdirection.ToUpper()} ").SetFont(times_new_roman);
                    Text degreeENG                    = new Text($"BACHELORS DEGREE OF INFORMATICS ENGINEERING ").SetFont(times_new_roman);
                    Text studiesdirectionENG          = new Text($"IN INFORMATICS ENGINEERING ").SetFont(times_new_roman);
                    Text partBeforeprogrammeENG       = new Text($"in {diploma.DateOfIssue.Year} completed bachelors study programme ").SetFont(times_new_roman);
                    Text programmepartENG             = new Text($"INFORMATION TECHNOLOGIES").SetFont(times_new_roman_bold);
                    Text programmerGovermentIDCodeENG = new Text($"(state code {diploma.StudiesProgrammeGovermentCode} )").SetFont(times_new_roman);
                    Text beforedegreepartENG          = new Text("and has been awarded").SetFont(times_new_roman);
                    //PDF construct
                    PageSize  pageSize = PageSize.A4.Rotate();
                    var       document = new Document(pdf, pageSize);
                    PdfCanvas canvas   = new PdfCanvas(pdf.AddNewPage());
                    canvas.AddImage(ImageDataFactory.Create(imageDestination), pageSize, false);
                    //document.Add(new Paragraph(diploma.LastName).SetFont(times_new_roman).SetFontSize(50).SetTextAlignment(TextAlignment.CENTER));
                    //document.Add(new Paragraph($"{diploma.Name.ToUpper()} {diploma.LastName.ToUpper()} (asmens kodas {diploma.IdentityNumber})").SetFont(times_new_roman).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER));
                    //Text spacing (fix it later)
                    document.Add(new Paragraph("\n \n \n").SetFont(times_new_roman).SetFontSize(50).SetTextAlignment(TextAlignment.CENTER).SetMultipliedLeading(1.0f));
                    document.Add(new Paragraph("\n \n").SetFont(times_new_roman).SetFontSize(25).SetTextAlignment(TextAlignment.CENTER).SetMultipliedLeading(1.0f));
                    document.Add(new Paragraph("\n").SetFont(times_new_roman).SetFontSize(15).SetTextAlignment(TextAlignment.CENTER).SetMultipliedLeading(1.0f));
                    document.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 0.5f));
                    //Text construct LT part
                    document.Add(new Paragraph().Add(namepart).Add(identitypart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(partBeforeprogramme).Add(programmepart).Add(programmerGovermentIDCode).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(beforedegreepart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(degreepart).Add(afterdegreepart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(studiesdirectionpart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph("\n").SetTextAlignment(TextAlignment.CENTER));
                    //Text construct ENG part
                    document.Add(new Paragraph().Add(namepart).Add(identitypartENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(partBeforeprogrammeENG).Add(programmepartENG).Add(programmerGovermentIDCodeENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(beforedegreepartENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(degreeENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(studiesdirectionENG).SetTextAlignment(TextAlignment.CENTER));
                    //Rector part
                    document.Add(new Paragraph().Add(rector).SetFontSize(11).SetTextAlignment(TextAlignment.LEFT).SetMultipliedLeading(1.0f));
                    //metadata part
                    //document.Add(new Paragraph().Add(dateofissueLT).SetFontSize(10).SetTextAlignment(TextAlignment.RIGHT).SetMultipliedLeading(0.8f));
                    //document.Add(new Paragraph().Add(dateofissueENG).SetFontSize(10).SetTextAlignment(TextAlignment.RIGHT).SetMultipliedLeading(0.8f));
                    Table table = new Table(2, true);
                    Style style = new Style().SetBorder(Border.NO_BORDER);
                    table.SetWidth(200);
                    table.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                    //table.AddCell(new Cell("Išdavimo data:").SetTextAlignment(TextAlignment.LEFT)).AddStyle(style);
                    //https://itextpdf.com/en/resources/faq/technical-support/itext-7/why-doesnt-getdefaultcellsetborderpdfpcellnoborder-have-any
                    //https://kodejava.org/how-do-i-create-table-cell-that-span-multiple-columns-in-itext/
                    table.AddCell(new Paragraph("Registracijos Nr").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph($"{diploma.RegistrationNr}").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Registracijos Nr").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Išdavimo data:").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph(diploma.DateOfIssue.ToString("yyyy/MM/dd")).SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Date of sssue:").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph(diploma.DateOfIssue.ToString("dd/MMMM/yyyy")).SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Code in system:").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph(diploma.quickSearch.ToString()).SetTextAlignment(TextAlignment.LEFT));
                    document.Add(table);
                    document.Close();
                    writer.Close();
                    return(stream);
                }
            //var stream = new MemoryStream();
        }