protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); // This method initializes an outline tree of the document and sets outline mode to true. pdfDoc.InitializeOutlines(); // Copier contains the logic to copy only acroform fields to a new page. // PdfPageFormCopier uses some caching logic which can potentially improve performance // in case of the reusing of the same instance. PdfPageFormCopier formCopier = new PdfPageFormCopier(); for (int i = 0; i < 3; i++) { // This method reads and renames form fields, // because the same source pdf with the same form fields will be copied. byte[] content = RenameFields(SRC, i + 1); IRandomAccessSource source = new RandomAccessSourceFactory().CreateSource(content); PdfDocument readerDoc = new PdfDocument(new PdfReader(source, new ReaderProperties())); readerDoc.CopyPagesTo(1, readerDoc.GetNumberOfPages(), pdfDoc, formCopier); readerDoc.Close(); } pdfDoc.Close(); }
public static void ProcessImage(ImageData image) { if (image.GetOriginalType() != ImageType.TIFF) { throw new ArgumentException("TIFF image expected"); } try { IRandomAccessSource ras; if (image.GetData() == null) { image.LoadData(); } ras = new RandomAccessSourceFactory().CreateSource(image.GetData()); RandomAccessFileOrArray raf = new RandomAccessFileOrArray(ras); TiffImageHelper.TiffParameters tiff = new TiffImageHelper.TiffParameters((TiffImageData)image); ProcessTiffImage(raf, tiff); raf.Close(); if (!tiff.jpegProcessing) { RawImageHelper.UpdateImageAttributes(tiff.image, tiff.additional); } } catch (System.IO.IOException e) { throw new iText.IO.IOException(iText.IO.IOException.TiffImageException, e); } }
protected void ManipulatePdf(String dest) { // CreateForm() method creates a temporary document in the memory, // which then will be used as a source while writing to a real document byte[] content = CreateForm(); IRandomAccessSource source = new RandomAccessSourceFactory().CreateSource(content); PdfDocument pdfDoc = new PdfDocument(new PdfReader(source, new ReaderProperties()), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); // Set a flag specifying whether to construct appearance streams and appearance dictionaries // for all widget annotations in the document. form.SetNeedAppearances(true); form.GetField("text1") // Method sets the flag, specifying whether or not the field can be changed. .SetReadOnly(true) .SetValue("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"); form.GetField("text2") .SetReadOnly(true) .SetValue("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"); form.GetField("text3") .SetReadOnly(true) .SetValue("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"); form.GetField("text4") .SetReadOnly(true) .SetValue("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"); pdfDoc.Close(); }
public virtual void TokenValueEqualsToTest() { String data = "SomeString"; RandomAccessSourceFactory factory = new RandomAccessSourceFactory(); PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(data.GetBytes()))); tok.NextToken(); NUnit.Framework.Assert.IsTrue(tok.TokenValueEqualsTo(data.GetBytes())); }
/// <summary> /// Pobieranie wartości zoom okna dla pliku, tak by zmieścił się w oknie /// </summary> /// <param name="pdfFile">plik dla którego należy obliczyć zoom</param> /// <param name="pdfRotation">rotacja strony PDF</param> /// <returns>wartość zoom</returns> private int GetFitZoom(byte[] pdfFile, out int pdfRotation) { double pdfPageSizeXPoint; // wielkość pliku w punktach double pdfPageSizeYPoint; // wielkość pliku w punktach IRandomAccessSource byteSource = new RandomAccessSourceFactory().CreateSource(pdfFile); using (PdfReader reader = new PdfReader(byteSource, new ReaderProperties())) using (PdfDocument pdfDoc = new PdfDocument(reader)) { pdfRotation = pdfDoc.GetPage(1).GetRotation(); switch (pdfRotation) { case 0: case 180: pdfPageSizeYPoint = pdfDoc.GetPage(1).GetPageSize().GetHeight(); // wielkość pliku w punktach pdfPageSizeXPoint = pdfDoc.GetPage(1).GetPageSize().GetWidth(); // wielkość pliku w punktach break; case 90: case 270: pdfPageSizeYPoint = pdfDoc.GetPage(1).GetPageSize().GetWidth(); // wielkość pliku w punktach pdfPageSizeXPoint = pdfDoc.GetPage(1).GetPageSize().GetHeight(); // wielkość pliku w punktach break; default: throw new Exception(@"Błędny kąt obrotu!"); } } byteSource.Close(); float dpiX; float dpiY; // pobranie rozdzielczości ekranu using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = graphics.DpiX; dpiY = graphics.DpiY; } double pdfPageSizeXPix = pdfPageSizeXPoint * dpiX / 72; // przeliczenie rozmiaru dokumentu z punktów na piksele double pdfPageSizeYPix = pdfPageSizeYPoint * dpiY / 72; // przeliczenie rozmiaru dokumentu z punktów na piksele int pdfViewerSizeYPix = pdfDocumentViewer.Height - 8; // - 8 bo okno ma wewnętrzny margines 4 z każdej strony int pdfViewerSizeXPix = pdfDocumentViewer.Width - 8; // - 8 bo okno ma wewnętrzny margines 4 z każdej strony double scaleX = pdfViewerSizeXPix / pdfPageSizeXPix * 100; // obliczenie współczynnika skalowania double scaleY = pdfViewerSizeYPix / pdfPageSizeYPix * 100; // obliczenie współczynnika skalowania return(scaleX < scaleY ? (int)Math.Floor(scaleX) : (int)Math.Floor(scaleY)); }
public virtual void EncodingTest() { RandomAccessSourceFactory factory; PdfTokenizer tok; PdfString pdfString; // hex string parse and check String testHexString = "<0D0A09557365729073204775696465>"; factory = new RandomAccessSourceFactory(); tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(testHexString.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1 )))); tok.NextToken(); pdfString = new PdfString(tok.GetByteContent(), tok.IsHexString()); NUnit.Framework.Assert.AreEqual("\r\n\tUser\u0090s Guide", pdfString.GetValue()); String testUnicodeString = "ΑΒΓΗ€•♣⋅"; pdfString = new PdfString(PdfEncodings.ConvertToBytes(testUnicodeString, PdfEncodings.UNICODE_BIG), false); NUnit.Framework.Assert.AreEqual(testUnicodeString, pdfString.ToUnicodeString()); pdfString = new PdfString("FEFF041F04400438043204350442".GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), true); NUnit.Framework.Assert.AreEqual("\u041F\u0440\u0438\u0432\u0435\u0442", pdfString.ToUnicodeString()); pdfString = new PdfString("FEFF041F04400438043204350442".GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), false); NUnit.Framework.Assert.AreEqual("FEFF041F04400438043204350442", pdfString.ToUnicodeString()); String specialCharacter = "\r\n\t\\n\\r\\t\\f"; pdfString = new PdfString(specialCharacter.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), false); NUnit.Framework.Assert.AreEqual("\n\t\n\r\t\f", pdfString.ToUnicodeString()); String symbol = "\u0001\u0004\u0006\u000E\u001F"; pdfString = new PdfString(symbol.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), false); NUnit.Framework.Assert.AreEqual(symbol, pdfString.ToUnicodeString()); String testString1 = "These\\\n two\\\r strings\\\n are the same"; pdfString = new PdfString(testString1.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), false); NUnit.Framework.Assert.AreEqual("These two strings are the same", pdfString.GetValue()); String testString2 = "This string contains \\245two octal characters\\307"; pdfString = new PdfString(testString2.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), false); NUnit.Framework.Assert.AreEqual("This string contains \u00A5two octal characters\u00C7", pdfString.GetValue ()); String testString3 = "\\0053"; pdfString = new PdfString(testString3.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), false); NUnit.Framework.Assert.AreEqual("\u00053", pdfString.GetValue()); String testString4 = "\\053"; pdfString = new PdfString(testString4.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1), false); NUnit.Framework.Assert.AreEqual("+", pdfString.GetValue()); byte[] b = new byte[] { (byte)46, (byte)56, (byte)40 }; pdfString = new PdfString(b, false); NUnit.Framework.Assert.AreEqual(iText.IO.Util.JavaUtil.GetStringForBytes(b), pdfString.GetValue()); }
/// <exception cref="System.Exception"/> private void CheckTokenTypes(String data, params PdfTokenizer.TokenType[] expectedTypes) { RandomAccessSourceFactory factory = new RandomAccessSourceFactory(); PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(data.GetBytes()))); for (int i = 0; i < expectedTypes.Length; i++) { tok.NextValidToken(); //System.out.println(tok.getTokenType() + " -> " + tok.getStringValue()); NUnit.Framework.Assert.AreEqual(expectedTypes[i], tok.GetTokenType(), "Position " + i); } }
public static string ExtractTextFromPdf(byte[] path) { var source = new RandomAccessSourceFactory().CreateSource(new MemoryStream(path).ToArray()); using (PdfReader reader = new PdfReader(source, new ReaderProperties())) using (PdfDocument pdfDoc = new PdfDocument(reader)) { StringBuilder text = new StringBuilder(); for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { var pageText = PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(i)); text.Append(pageText); } return(text.ToString()); } }
public static void ProcessImage(ImageData jbig2) { if (jbig2.GetOriginalType() != ImageType.JBIG2) { throw new ArgumentException("JBIG2 image expected"); } Jbig2ImageData image = (Jbig2ImageData)jbig2; try { IRandomAccessSource ras; if (image.GetData() == null) { image.LoadData(); } ras = new RandomAccessSourceFactory().CreateSource(image.GetData()); RandomAccessFileOrArray raf = new RandomAccessFileOrArray(ras); Jbig2SegmentReader sr = new Jbig2SegmentReader(raf); sr.Read(); Jbig2SegmentReader.Jbig2Page p = sr.GetPage(image.GetPage()); raf.Close(); image.SetHeight(p.pageBitmapHeight); image.SetWidth(p.pageBitmapWidth); image.SetBpc(1); image.SetColorSpace(1); //TODO JBIG2 globals caching byte[] globals = sr.GetGlobal(true); //TODO due to the fact, that streams now may be transformed to indirect objects only on writing, //pdfStream.getDocument() cannot longer be the sign of inline/indirect images // in case inline image pdfStream.getDocument() will be null if (globals != null) { /*&& stream.getDocument() != null*/ IDictionary <String, Object> decodeParms = new Dictionary <String, Object>(); // PdfStream globalsStream = new PdfStream().makeIndirect(pdfStream.getDocument()); // globalsStream.getOutputStream().write(globals); decodeParms["JBIG2Globals"] = globals; image.decodeParms = decodeParms; } image.SetFilter("JBIG2Decode"); image.SetColorSpace(1); image.SetBpc(1); image.data = p.GetData(true); } catch (System.IO.IOException e) { throw new iText.IO.IOException(iText.IO.IOException.Jbig2ImageException, e); } }
/// <summary> /// Obsługa zapisywania plików wynikowych /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonSave_Click(object sender, EventArgs e) { bool nullPrefix = Global.ScanFiles.Values.Any(o => string.IsNullOrEmpty(o.Prefix)); // czy wszystkie skany zostały zindeksowane if (nullPrefix) { MessageBox.Show(@"Nie wszystkie skany zostały zindeksowane!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string outputDirectory = Path.Combine(Global.LastDirectory, textBoxOperat.Text); // folder wyjściowy na podstawie nazwy wpisanej w polu operat i katalogu ze skanami Directory.CreateDirectory(outputDirectory); // utwórz folder wynikowy List <ScanFile> scanFilesWithoutSkip = Global.ScanFiles.Values.Where(skan => skan.Prefix != "skip").ToList(); for (int i = 0; i < scanFilesWithoutSkip.Count; i++) { IRandomAccessSource byteSource = new RandomAccessSourceFactory().CreateSource(scanFilesWithoutSkip[i].PdfFile); PdfReader pdfReader = new PdfReader(byteSource, new ReaderProperties()); MemoryStream memoryStreamOutput = new MemoryStream(); PdfWriter pdfWriter = new PdfWriter(memoryStreamOutput); PdfDocument pdfDoc = new PdfDocument(pdfReader, pdfWriter); PdfDocumentInfo info = pdfDoc.GetDocumentInfo(); info.SetCreator("GISNET ScanHelper"); pdfDoc.Close(); string fileName = textBoxOperat.Text + "_" + (i + 1) + "-" + scanFilesWithoutSkip[i].Prefix + "-" + scanFilesWithoutSkip[i].TypeCounter.ToString().PadLeft(3, '0') + Path.GetExtension(scanFilesWithoutSkip[i].FileName); File.WriteAllBytes(Path.Combine(outputDirectory, fileName), memoryStreamOutput.ToArray()); } MessageBox.Show("Pliki zapisano!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); }
protected void ManipulatePdf(String dest) { // createForm() method creates a temporary document in the memory, // which then will be used as a source while writing to a real document byte[] content = CreateForm(); IRandomAccessSource source = new RandomAccessSourceFactory().CreateSource(content); PdfDocument pdfDoc = new PdfDocument(new PdfReader(source, new ReaderProperties()), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); form.GetField(FIELD_NAME) .SetValue("A B C D E F\nG H I J K L M N\nO P Q R S T U\r\nV W X Y Z\n\nAlphabet street"); // If no fields have been explicitly included, then all fields are flattened. // Otherwise only the included fields are flattened. form.FlattenFields(); pdfDoc.Close(); }
static void Main(string[] args) { PdfWriter writer = new PdfWriter("C:\\Users\\Bill\\Desktop\\out.pdf"); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf); Uri tiffFqn = UrlUtil.ToURL("C:\\Users\\Bill\\Desktop\\Multipage Test Image.tif"); IRandomAccessSource iRandomAccessSource = new RandomAccessSourceFactory().CreateSource(tiffFqn); RandomAccessFileOrArray randomAccessFileOrArray = new RandomAccessFileOrArray(iRandomAccessSource); int tiffPageCount = TiffImageData.GetNumberOfPages(randomAccessFileOrArray); for (int i = 1; i <= tiffPageCount; i++) { Image tiffPage = new Image(ImageDataFactory.CreateTiff(tiffFqn, true, i, true)); document.Add(tiffPage); } document.Close(); }
public virtual void CreatePdf(String dest) { PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); Document document = new Document(pdf); Image img; // Animated GIF Uri url1 = UrlUtil.ToURL(TEST1); IList <ImageData> list = ImageDataFactory.CreateGifFrames(url1); foreach (ImageData data in list) { img = new iText.Layout.Element.Image(data); document.Add(img); } // JBIG2 Uri url2 = UrlUtil.ToURL(TEST2); IRandomAccessSource ras2 = new RandomAccessSourceFactory().CreateSource(url2); RandomAccessFileOrArray raf2 = new RandomAccessFileOrArray(ras2); int pages2 = Jbig2ImageData.GetNumberOfPages(raf2); for (int i = 1; i <= pages2; i++) { img = new iText.Layout.Element.Image(ImageDataFactory.CreateJbig2(url2, i)); document.Add(img); } // TIFF Uri url3 = UrlUtil.ToURL(TEST3); IRandomAccessSource ras3 = new RandomAccessSourceFactory().CreateSource(url3); RandomAccessFileOrArray raf3 = new RandomAccessFileOrArray(ras3); int pages3 = TiffImageData.GetNumberOfPages(raf3); for (int i_1 = 1; i_1 <= pages3; i_1++) { img = new iText.Layout.Element.Image(ImageDataFactory.CreateTiff(url3, true, i_1, true)); document.Add(img); } document.Close(); }
public virtual void InnerArraysInContentStreamTest() { String inputFileName = sourceFolder + "innerArraysInContentStream.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFileName)); byte[] docInBytes = pdfDocument.GetFirstPage().GetContentBytes(); RandomAccessSourceFactory factory = new RandomAccessSourceFactory(); PdfTokenizer tokeniser = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(docInBytes))); PdfResources resources = pdfDocument.GetPage(1).GetResources(); PdfCanvasParser ps = new PdfCanvasParser(tokeniser, resources); IList <PdfObject> actual = ps.Parse(null); IList <PdfObject> expected = new List <PdfObject>(); expected.Add(new PdfString("Cyan")); expected.Add(new PdfArray(new int[] { 1, 0, 0, 0 })); expected.Add(new PdfString("Magenta")); expected.Add(new PdfArray(new int[] { 0, 1, 0, 0 })); expected.Add(new PdfString("Yellow")); expected.Add(new PdfArray(new int[] { 0, 0, 1, 0 })); PdfArray cmpArray = new PdfArray(expected); NUnit.Framework.Assert.IsTrue(new CompareTool().CompareArrays(cmpArray, (((PdfDictionary)actual[1]).GetAsArray (new PdfName("ColorantsDef"))))); }
/// <summary> /// Wstawianie znaku wodnego do przekazanego pliku /// </summary> /// <param name="pdfFile">Plik do którego należy wstawić znak wodny</param> /// <returns></returns> private void SetWatermarkPdf(byte[] pdfFile) { IRandomAccessSource byteSource = new RandomAccessSourceFactory().CreateSource(pdfFile); PdfReader pdfReader = new PdfReader(byteSource, new ReaderProperties()); MemoryStream memoryStreamOutput = new MemoryStream(); PdfWriter pdfWriter = new PdfWriter(memoryStreamOutput); PdfDocument pdfDoc = new PdfDocument(pdfReader, pdfWriter); FontProgram fontProgram = new TrueTypeFont(Resources.arial); PdfFont pdfFont = PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H, true); PdfCanvas over = new PdfCanvas(pdfDoc.GetFirstPage()); over.SetFillColor(ColorConstants.BLACK); Paragraph p = new Paragraph(File.ReadAllText("stopka.txt")); p.SetFont(pdfFont); p.SetFontSize(8); p.SetFixedLeading(8); over.SaveState(); PdfExtGState gs1 = new PdfExtGState(); gs1.SetFillOpacity(0.2f); gs1.SetStrokeOpacity(0.2f); over.SetExtGState(gs1); int pageRotation = pdfDoc.GetPage(1).GetRotation(); float textAngleRad = (float)(pageRotation * Math.PI / 180.0); float pageWidth = pdfDoc.GetPage(1).GetPageSizeWithRotation().GetWidth(); float pageHeight = pdfDoc.GetPage(1).GetPageSizeWithRotation().GetHeight(); using (Canvas stopka = new Canvas(over, pdfDoc, pdfDoc.GetPage(1).GetPageSizeWithRotation())) { switch (pageRotation) { case 0: stopka.ShowTextAligned(p, pageWidth / 2, 8, 1, TextAlignment.CENTER, VerticalAlignment.BOTTOM, textAngleRad); break; case 90: stopka.ShowTextAligned(p, pageHeight - 8, pageWidth / 2, 1, TextAlignment.CENTER, VerticalAlignment.BOTTOM, textAngleRad); break; case 180: stopka.ShowTextAligned(p, pageWidth / 2, pageHeight - 8, 1, TextAlignment.CENTER, VerticalAlignment.BOTTOM, textAngleRad); break; case 270: stopka.ShowTextAligned(p, 8, pageWidth / 2, 1, TextAlignment.CENTER, VerticalAlignment.BOTTOM, textAngleRad); break; default: throw new Exception("Błędny kąt obrotu strony"); } } over.RestoreState(); pdfDoc.Close(); Global.ScanFiles[Global.IdSelectedFile].PdfFile = memoryStreamOutput.ToArray(); byteSource.Close(); memoryStreamOutput.Close(); pdfReader.Close(); pdfWriter.Close(); }
/// <summary> /// Obsługa zdarzenia kliknięcia myszką na przycisku obrotu dokumentu, lub skrótu klawiszowego /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnRotate_ClickOrKeyPress(object sender, EventArgs e) { // jeśli nie ma plików na liście to nic nie rób if (listBoxFiles.Items.Count <= 0) { return; } int desiredRot = 0; // jeśli obracanie zostało wywołane klawiszem if (e.GetType() == typeof(KeyEventArgs)) { KeyEventArgs arg = (KeyEventArgs)e; switch (arg.KeyData) { case Keys.Control | Keys.Right: desiredRot = 90; break; case Keys.Control | Keys.Left: desiredRot = 270; break; } } if (e.GetType() == typeof(MouseEventArgs)) // jeśli obracanie zostało wywołane myszką { MouseEventArgs arg = (MouseEventArgs)e; switch (arg.Button) { case MouseButtons.Left: desiredRot = 270; break; case MouseButtons.Right: desiredRot = 90; break; } } IRandomAccessSource byteSource = new RandomAccessSourceFactory().CreateSource(Global.ScanFiles[Global.IdSelectedFile].PdfFile); PdfReader pdfReader = new PdfReader(byteSource, new ReaderProperties()); MemoryStream memoryStreamOutput = new MemoryStream(); PdfWriter pdfWriter = new PdfWriter(memoryStreamOutput); PdfDocument pdfDoc = new PdfDocument(pdfReader, pdfWriter); PdfPage page = pdfDoc.GetPage(1); var rotate = page.GetPdfObject().GetAsNumber(PdfName.Rotate); if (rotate == null) { page.SetRotation(desiredRot); } else { page.SetRotation((rotate.IntValue() + desiredRot) % 360); } pdfDoc.Close(); Global.ScanFiles[Global.IdSelectedFile].PdfFile = memoryStreamOutput.ToArray(); // Przypisz nowy dokument do klasy obiektów ze skanami if (Global.SaveRotation) { File.WriteAllBytes(Global.ScanFiles[Global.IdSelectedFile].PathAndFileName, memoryStreamOutput.ToArray()); // zapisz nowy plik na dysku w miejsce starego } byteSource.Close(); memoryStreamOutput.Close(); pdfReader.Close(); pdfWriter.Close(); // Wyświetl nowy plik w oknie podglądu Global.Zoom = GetFitZoom(Global.ScanFiles[Global.IdSelectedFile].PdfFile, out int _); pdfDocumentViewer.LoadFromStream(new MemoryStream(Global.ScanFiles[Global.IdSelectedFile].PdfFile)); pdfDocumentViewer.ZoomTo(Global.Zoom); pdfDocumentViewer.EnableHandTool(); }
public byte[] Add(string infile, string outFile) { PdfFont baseFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false); Rectangle pageSize; string NoOfPagesPadded = string.Empty; string PageNoPadded = string.Empty; string HdrLeft = string.Empty; string HdrRight = string.Empty; int xLeft = 30; int xRight = 110; //was 100 int xTop = 30; float watermarkTrimmingRectangleWidth; //= 300; float watermarkTrimmingRectangleHeight = 300; float formXOffset = 0; float formYOffset = -5; // was zero set to -5 because dangling letters (e.g. g) were being cut-off byte[] outByteFile; byte[] inByteFile = null; try { inByteFile = File.ReadAllBytes(infile); IRandomAccessSource inSourceFile = new RandomAccessSourceFactory().CreateSource(inByteFile); using (PdfReader reader = new PdfReader(inSourceFile, new ReaderProperties()).SetUnethicalReading(true)) { using (var outMemoryFile = new MemoryStream()) { using (PdfWriter pdfWrite = new PdfWriter(outMemoryFile)) { using (PdfDocument pdfDoc = new PdfDocument(reader, pdfWrite)) { using (Document doc = new Document(pdfDoc)) { int n = pdfDoc.GetNumberOfPages(); for (var i = 1; i <= n; i++) { // Remove annotation if it exists PdfDictionary pageDict = pdfDoc.GetPage(i).GetPdfObject(); PdfArray annots = pageDict.GetAsArray(PdfName.Annots); if (annots != null) { for (int j = 0; j < annots.Size(); j++) { PdfDictionary annotation = annots.GetAsDictionary(j); if (PdfName.Watermark.Equals(annotation.GetAsName(PdfName.Subtype))) { string NMvalue = annotation.GetAsString(PdfName.NM).GetValue(); if (NMvalue == AnnotName) { annotation.Clear(); } } } } } for (int i = 1; i <= n; i++) { PdfPage page = pdfDoc.GetPage(i); pageSize = page.GetMediaBox(); watermarkTrimmingRectangleWidth = pageSize.GetWidth(); float PageWidth = pageSize.GetWidth(); float PageHeight = pageSize.GetHeight(); int rotation = page.GetRotation(); Rectangle watermarkTrimmingRectangle = new Rectangle(pageSize.GetLeft() + xLeft, pageSize.GetTop() - xTop, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight); PdfWatermarkAnnotation watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle); watermark.SetName(new PdfString(AnnotName)); Rectangle formRectangle = new Rectangle(formXOffset, formYOffset, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight); PdfFormXObject form = new PdfFormXObject(formRectangle); //Observation: font XObject will be resized to fit inside the watermark rectangle. If it is larger, your text will be stretched. PdfCanvas canvasOver = new PdfCanvas(form, pdfDoc); canvasOver.SetFillColor(iText.Kernel.Colors.ColorConstants.RED); canvasOver.SetFontAndSize(baseFont, 10); canvasOver.SaveState(); string SDSNo = "z2345678"; HdrLeft = CompanyName + $" SDS# {SDSNo}"; // HdrLeft = $"PWidth: {PageWidth.ToString()} rotation: {rotation.ToString()}"; //qqtempqq NoOfPagesPadded = (n.ToString()); PageNoPadded = i.ToString(); HdrRight = $"Page {PageNoPadded} of {NoOfPagesPadded}"; // HdrRight = $"PHeight: {PageHeight.ToString()}"; //qqtempqq canvasOver.BeginText() .SetColor(iText.Kernel.Colors.ColorConstants.RED, true) .SetFontAndSize(baseFont, 10) .ShowText(HdrLeft) .EndText(); canvasOver.BeginText() .MoveText(formRectangle.GetRight() - xRight, 0) .SetColor(iText.Kernel.Colors.ColorConstants.RED, true) .SetFontAndSize(baseFont, 10) .ShowText(HdrRight) .EndText(); canvasOver.SaveState(); canvasOver.RestoreState(); canvasOver.Release(); watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject())); watermark.SetFlags(PdfAnnotation.PRINT); page.AddAnnotation(watermark); } } } outByteFile = outMemoryFile.ToArray(); } } } File.WriteAllBytes(outFile, outByteFile); } catch (Exception ex) { Console.WriteLine("Error:" + ex.ToString()); return(inByteFile); throw; } return(outByteFile); }
public virtual void PrimitivesTest() { String data = "<</Size 70." + "/Value#20 .1" + "/Root 46 0 R" + "/Info 44 0 R" + "/ID[<736f6d652068657820737472696e672>(some simple string )<8C2547D58D4BD2C6F3D32B830BE3259D2>-70.1--0.2]" + "/Name1 --15" + "/Prev ---116.23 >>"; RandomAccessSourceFactory factory = new RandomAccessSourceFactory(); PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(data.GetBytes(iText.IO.Util.EncodingUtil.ISO_8859_1 )))); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.StartDic); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name); PdfName name = new PdfName(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("Size", name.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number); PdfNumber num = new PdfNumber(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("70.", num.ToString()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name); name = new PdfName(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("Value ", name.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number); num = new PdfNumber(tok.GetByteContent()); NUnit.Framework.Assert.AreNotSame("0.1", num.ToString()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name); name = new PdfName(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("Root", name.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Ref); PdfIndirectReference @ref = new PdfIndirectReference(null, tok.GetObjNr(), tok.GetGenNr()); NUnit.Framework.Assert.AreEqual("46 0 R", @ref.ToString()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name); name = new PdfName(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("Info", name.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Ref); @ref = new PdfIndirectReference(null, tok.GetObjNr(), tok.GetGenNr()); NUnit.Framework.Assert.AreEqual("44 0 R", @ref.ToString()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name); name = new PdfName(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("ID", name.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.StartArray); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.String); NUnit.Framework.Assert.AreEqual(tok.IsHexString(), true); PdfString str = new PdfString(tok.GetByteContent(), tok.IsHexString()); NUnit.Framework.Assert.AreEqual("some hex string ", str.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.String); NUnit.Framework.Assert.AreEqual(tok.IsHexString(), false); str = new PdfString(tok.GetByteContent(), tok.IsHexString()); NUnit.Framework.Assert.AreEqual("some simple string ", str.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.String); NUnit.Framework.Assert.AreEqual(tok.IsHexString(), true); str = new PdfString(tok.GetByteContent(), tok.IsHexString()); NUnit.Framework.Assert.AreEqual("\u008C%G\u00D5\u008DK\u00D2\u00C6\u00F3\u00D3+\u0083\u000B\u00E3%\u009D " , str.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number); num = new PdfNumber(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("-70.1", num.ToString()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number); num = new PdfNumber(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("-0.2", num.ToString()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.EndArray); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name); name = new PdfName(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("Name1", name.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number); num = new PdfNumber(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("0", num.ToString()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Name); name = new PdfName(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("Prev", name.GetValue()); tok.NextValidToken(); NUnit.Framework.Assert.AreEqual(tok.GetTokenType(), PdfTokenizer.TokenType.Number); num = new PdfNumber(tok.GetByteContent()); NUnit.Framework.Assert.AreEqual("-116.23", num.ToString()); }
/// <summary>Gets the document bytes that are hashable when using external signatures.</summary> /// <remarks> /// Gets the document bytes that are hashable when using external signatures. /// The general sequence is: /// <see cref="PreClose(System.Collections.Generic.IDictionary{K, V})"/> /// , /// <see cref="GetRangeStream()"/> /// and /// <see cref="Close(iText.Kernel.Pdf.PdfDictionary)"/> /// . /// </remarks> /// <returns> /// The /// <see cref="System.IO.Stream"/> /// of bytes to be signed. /// </returns> /// <exception cref="System.IO.IOException"/> protected internal virtual Stream GetRangeStream() { RandomAccessSourceFactory fac = new RandomAccessSourceFactory(); return(new RASInputStream(fac.CreateRanged(GetUnderlyingSource(), range))); }
/// <summary>Gets the number of pages the TIFF document has.</summary> /// <param name="bytes">a byte array containing a TIFF image.</param> /// <returns>the number of pages.</returns> public static int GetNumberOfPages(byte[] bytes) { IRandomAccessSource ras = new RandomAccessSourceFactory().CreateSource(bytes); return(GetNumberOfPages(new RandomAccessFileOrArray(ras))); }
/// <summary>Returns the underlying source.</summary> /// <returns>The underlying source</returns> /// <exception cref="System.IO.IOException"/> protected internal virtual IRandomAccessSource GetUnderlyingSource() { RandomAccessSourceFactory fac = new RandomAccessSourceFactory(); return(raf == null?fac.CreateSource(bout) : fac.CreateSource(raf)); }