Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aspose.PDF for .NET
Gist for Aspose.PDF for .NET
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
Document doc = new Document(dataDir + "blank.pdf");
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature())
{
pdfSign.BindPdf(doc);
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0]);
pdfSign.SignatureAppearance = dataDir + "demo.png";
pdfSign.Sign(1, "Reason", "Contact", "Location", true, new System.Drawing.Rectangle(100, 100, 200, 200), externalSignature);
pdfSign.Save(dataDir + "externalSignature2.pdf");
}
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature(new Document(dataDir + "externalSignature2.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
File.Copy(dataDir + "blank.pdf", dataDir + "externalSignature1.pdf", true);
using (FileStream fs = new FileStream(dataDir + "externalSignature1.pdf", FileMode.Open, FileAccess.ReadWrite))
{
using (Document doc = new Document(fs))
{
SignatureField field1 = new SignatureField(doc.Pages[1], new Rectangle(100, 400, 10, 10));
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0])
{
Authority = "Me",
Reason = "Reason",
ContactInfo = "Contact"
};
field1.PartialName = "sig1";
doc.Form.Add(field1, 1);
field1.Sign(externalSignature);
doc.Save();
}
}
using (PdfFileSignature pdfSign = new PdfFileSignature(new Document(dataDir + "externalSignature1.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document();
Page pdfPage = doc.Pages.Add();
System.Drawing.Rectangle drect = new System.Drawing.Rectangle();
drect.Height = (int)pdfPage.Rect.Height;
drect.Width = (int)pdfPage.Rect.Width;
drect.X = 0;
drect.Y = 0;
Aspose.Pdf.Rectangle arect = Aspose.Pdf.Rectangle.FromRect(drect);
IList<Point[]> inkList = new List<Point[]>();
Aspose.Pdf.Point[] arrpt = new Aspose.Pdf.Point[3];
inkList.Add(arrpt);
arrpt[0] = new Aspose.Pdf.Point(100, 800);
arrpt[1] = new Aspose.Pdf.Point(200, 800);
arrpt[2] = new Aspose.Pdf.Point(200, 700);
InkAnnotation ia = new InkAnnotation(pdfPage, arect, inkList);
ia.Title = "XXX";
ia.Color = Aspose.Pdf.Color.LightBlue; // (GetColorFromString(stroke.InkColor));
ia.CapStyle = CapStyle.Rounded;
Border border = new Border(ia);
border.Width = 25;
ia.Opacity = 0.5;
pdfPage.Annotations.Add(ia);
dataDir = dataDir + "AddlnkAnnotation_out.pdf";
// Save output file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document(dataDir + "ExtractHighlightedText.pdf");
// Loop through all the annotations
foreach (Annotation annotation in doc.Pages[1].Annotations)
{
// Filter TextMarkupAnnotation
if (annotation is TextMarkupAnnotation)
{
TextMarkupAnnotation highlightedAnnotation = annotation as TextMarkupAnnotation;
// Retrieve highlighted text fragments
TextFragmentCollection collection = highlightedAnnotation.GetMarkedTextFragments();
foreach (TextFragment tf in collection)
{
// Display highlighted text
Console.WriteLine(tf.Text);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
// Open document
Document doc = new Document(dataDir + "AddAnnotation.pdf");
//Create annotation
ScreenAnnotation sa = new ScreenAnnotation(doc.Pages[1], new Rectangle(100, 400, 300, 600), dataDir + "AddSwfFileAsAnnotation.swf");
doc.Pages[1].Annotations.Add(sa);
// Save Doucument
doc.Save(dataDir + "GetResourceOfAnnotation_Out.pdf");
// Open document
Document doc1 = new Document(dataDir + "GetResourceOfAnnotation_Out.pdf");
//Get action of the annotation
RenditionAction action = (doc.Pages[1].Annotations[1] as ScreenAnnotation).Action as RenditionAction;
//Get rendition of the rendition action
Rendition rendition = ((doc.Pages[1].Annotations[1] as ScreenAnnotation).Action as RenditionAction).Rendition;
//Media Clip
MediaClip clip = (rendition as MediaRendition).MediaClip;
FileSpecification data = (clip as MediaClipData).Data;
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[1024];
int read = 0;
//Data of media are accessible in FileSpecification.Contents
Stream source = data.Contents;
while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
Console.WriteLine(rendition.Name);
Console.WriteLine(action.RenditionOperation);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document();
doc.Pages.Add();
IList<Point[]> inkList = new List<Point[]>();
LineInfo lineInfo = new LineInfo();
lineInfo.VerticeCoordinate = new float[] { 55, 55, 70, 70, 70, 90, 150, 60 };
lineInfo.Visibility = true;
lineInfo.LineColor = System.Drawing.Color.Red;
lineInfo.LineWidth = 2;
int length = lineInfo.VerticeCoordinate.Length / 2;
Aspose.Pdf.Point[] gesture = new Aspose.Pdf.Point[length];
for (int i = 0; i < length; i++)
{
gesture[i] = new Aspose.Pdf.Point(lineInfo.VerticeCoordinate[2 * i], lineInfo.VerticeCoordinate[2 * i + 1]);
}
inkList.Add(gesture);
InkAnnotation a1 = new InkAnnotation(doc.Pages[1], new Aspose.Pdf.Rectangle(100, 100, 300, 300), inkList);
a1.Subject = "Test";
a1.Title = "Title";
a1.Color = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green);
Border border = new Border(a1);
border.Width = 3;
border.Effect = BorderEffect.Cloudy;
border.Dash = new Dash(1, 1);
border.Style = BorderStyle.Solid;
doc.Pages[1].Annotations.Add(a1);
dataDir = dataDir + "lnkAnnotationLineWidth_out.pdf";
// Save output file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document();
Page page = doc.Pages.Add();
DefaultAppearance da = new DefaultAppearance();
da.TextColor = System.Drawing.Color.Red;
da.FontSize = 10;
FreeTextAnnotation fta = new FreeTextAnnotation(page, new Rectangle(422.25, 645.75, 583.5, 702.75), da);
fta.Intent = FreeTextIntent.FreeTextCallout;
fta.EndingStyle = LineEnding.OpenArrow;
fta.Callout = new Point[]
{
new Point(428.25,651.75), new Point(462.75,681.375), new Point(474,681.375)
};
page.Annotations.Add(fta);
fta.RichText = "<body xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:APIVersion=\"Acrobat:11.0.23\" xfa:spec=\"2.0.2\" style=\"color:#FF0000;font-weight:normal;font-style:normal;font-stretch:normal\"><p dir=\"ltr\"><span style=\"font-size:9.0pt;font-family:Helvetica\">This is a sample</span></p></body>";
doc.Save(dataDir + "SetCalloutProperty.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document pdfDocument = new Document( dataDir + "AddAnnotation.pdf");
StringBuilder Xfdf = new StringBuilder();
Xfdf.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?><xfdf xmlns=\"http://ns.adobe.com/xfdf/\" xml:space=\"preserve\"><annots>");
CreateXfdf(ref Xfdf);
Xfdf.AppendLine("</annots></xfdf>");
pdfDocument.ImportAnnotationsFromXfdf(new MemoryStream(Encoding.UTF8.GetBytes(Xfdf.ToString())));
pdfDocument.Save(dataDir + "SetCalloutPropertyXFDF.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Open Markdown document
Document doc = new Document(dataDir + "sample.md", new MdLoadOptions());
// Save document in PDF format
doc.Save(dataDir + "MarkdownToPDF.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
using (FileStream fileStream = new FileStream(dataDir + "sample.pcl", FileMode.Open))
using (MemoryStream memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
using (Document document = new Document(memoryStream, new PclLoadOptions()))
{
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Load PDF document
Document pdfDocument = new Document(dataDir + "input.pdf");
// Instantiate ExcelSave Option object
Aspose.Pdf.ExcelSaveOptions excelsave = new ExcelSaveOptions();
excelsave.Format = ExcelSaveOptions.ExcelFormat.XLSX;
// Save the output in XLS format
pdfDocument.Save("PDFToXLSX_out.xlsx", excelsave);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
using (Document pdfDocument = new Document(dataDir + "input.pdf"))
{
using (FileStream imageStream = new FileStream(dataDir + "SetDefaultFontName.png", FileMode.Create))
{
Resolution resolution = new Resolution(300);
PngDevice pngDevice = new PngDevice(resolution);
RenderingOptions ro = new RenderingOptions();
ro.DefaultFontName = "Arial";
pngDevice.RenderingOptions = ro;
pngDevice.Process(pdfDocument.Pages[1], imageStream);
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Load source PDF form
Document doc = new Document(dataDir + "input.pdf");
// Flatten Forms
if (doc.Form.Fields.Count() > 0)
{
foreach (var item in doc.Form.Fields)
{
item.Flatten();
}
}
dataDir = dataDir + "FlattenForms_out.pdf";
// Save the updated document
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir+ "AddImage.pdf");
// Set coordinates
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;
// Get the page where image needs to be added
Page page = pdfDocument.Pages[1];
// Load image into stream
FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open);
// Add image to Images collection of Page Resources
page.Resources.Images.Add(imageStream);
// Using GSave operator: this operator saves current graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Create Rectangle and Matrix objects
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });
// Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
// Using Do operator: this operator draws image
page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
// Using GRestore operator: this operator restores graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
dataDir = dataDir + "AddImage_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Retrieve names of all the PDF files in a particular directory
string[] fileEntries = Directory.GetFiles(dataDir, "*.pdf");
// Iterate through all the files entries in array
for (int counter = 0; counter < fileEntries.Length; counter++)
{
//Open document
Document pdfDocument = new Document(fileEntries[counter]);
for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
{
using (FileStream imageStream = new FileStream(dataDir + "\\Thumbanils" + counter.ToString() + "_" + pageCount + ".jpg", FileMode.Create))
{
//Create Resolution object
Resolution resolution = new Resolution(300);
//JpegDevice jpegDevice = new JpegDevice(500, 700, resolution, 100);
JpegDevice jpegDevice = new JpegDevice(45, 59, resolution, 100);
//Convert a particular page and save the image to stream
jpegDevice.Process(pdfDocument.Pages[pageCount], imageStream);
//Close stream
imageStream.Close();
}
}
}
// Acrobat objects
Acrobat.CAcroPDDoc pdfDoc;
Acrobat.CAcroPDPage pdfPage;
Acrobat.CAcroRect pdfRect;
Acrobat.CAcroPoint pdfPoint;
AppSettingsReader appSettings = new AppSettingsReader();
string pdfInputPath = appSettings.GetValue("pdfInputPath", typeof(string)).ToString();
string pngOutputPath = appSettings.GetValue("pngOutputPath", typeof(string)).ToString();
string templatePortraitFile = Application.StartupPath + @"\pdftemplate_portrait.gif";
string templateLandscapeFile = Application.StartupPath + @"\pdftemplate_portrait.gif"; ;
try
{
// Get list of files to process from the input path
// Could change to read list from database instead
string[] files = Directory.GetFiles(pdfInputPath, "*.pdf");
for(int n = 0; n<files.Length; n++)
{
string inputFile = files[n].ToString();
string outputFile = pngOutputPath + files[n].Substring(files[n].LastIndexOf(@"\") + 1).Replace(".pdf", ".png");
/* Could skip if thumbnail already exists in output path
FileInfo fi = new FileInfo(inputFile);
if (!fi.Exists) {} */
// Create the document (Can only create the AcroExch.PDDoc object using late-binding)
// Note using VisualBasic helper functions, have to add reference to DLL in
// C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll
// Will always be available as .NET framework ships with all
pdfDoc = (Acrobat.CAcroPDDoc) Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");
int ret = pdfDoc.Open(inputFile);
if (ret == 0)
{
throw new FileNotFoundException();
}
// Get the number of pages (to be used later if you wanted to store that information)
int pageCount = pdfDoc.GetNumPages();
// Get the first page
pdfPage = (Acrobat.CAcroPDPage) pdfDoc.AcquirePage(0);
pdfPoint = (Acrobat.CAcroPoint) pdfPage.GetSize();
pdfRect = (Acrobat.CAcroRect) Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");
pdfRect.Left = 0;
pdfRect.right = pdfPoint.x;
pdfRect.Top = 0;
pdfRect.bottom = pdfPoint.y;
// Render to clipboard, scaled by 100 percent (ie. original size)
// Even though we want a smaller image, better for us to scale in .NET
// than Acrobat as it would greek out small text
// see http://www.adobe.com/support/techdocs/1dd72.htm
pdfPage.CopyToClipboard(pdfRect, 0, 0, 100);
IDataObject clipboardData = Clipboard.GetDataObject();
if (clipboardData.GetDataPresent(DataFormats.Bitmap))
{
Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);
// Size of generated thumbnail in pixels
int thumbnailWidth = 45;
int thumbnailHeight = 59;
string templateFile;
// Switch between portrait and landscape
if (pdfPoint.x<pdfPoint.y)
{
templateFile = templatePortraitFile;
}
else
{
templateFile = templateLandscapeFile;
// Swap width and height (little trick not using third temp variable)
thumbnailWidth = thumbnailWidth ^ thumbnailHeight;
thumbnailHeight = thumbnailWidth ^ thumbnailHeight;
thumbnailWidth = thumbnailWidth ^ thumbnailHeight;
}
// Load the template graphic
Bitmap templateBitmap = new Bitmap(templateFile);
// Render to small image using the bitmap class
Image pdfImage = pdfBitmap.GetThumbnailImage(thumbnailWidth, thumbnailHeight, null, IntPtr.Zero);
// Create new blank bitmap (+ 7 for template border)
Bitmap thumbnailBitmap = new Bitmap(thumbnailWidth + 7, thumbnailHeight + 7,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// To overlayout the template with the image, we need to set the transparency
// http://www.sellsbrothers.com/writing/default.aspx?content=dotnetimagerecoloring.htm
templateBitmap.MakeTransparent();
using (Graphics thumbnailGraphics = Graphics.FromImage(thumbnailBitmap))
{
// Draw rendered pdf image to new blank bitmap
thumbnailGraphics.DrawImage(pdfImage, 2, 2, thumbnailWidth, thumbnailHeight);
// Draw template outline over the bitmap (pdf with show through the transparent area)
thumbnailGraphics.DrawImage(templateBitmap, 0, 0);
// Save as .png file
thumbnailBitmap.Save(outputFile, System.Drawing.Imaging.ImageFormat.Png);
Console.WriteLine("Generated thumbnail... {0}", outputFile);
}
pdfDoc.Close();
// Not sure how why it is to do this, but Acrobat is not the best behaved COM object
// see http://blogs.msdn.com/yvesdolc/archive/2004/04/17/115379.aspx
Marshal.ReleaseComObject(pdfPage);
Marshal.ReleaseComObject(pdfRect);
Marshal.ReleaseComObject(pdfDoc);
}
}
}
catch (System.Exception ex)
{
Console.Write(ex.ToString());
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Initialize Time
var time = DateTime.Now.Ticks;
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir + "Shrinkimage.pdf");
// Initialize OptimizationOptions
var optimizeOptions = new Pdf.Optimization.OptimizationOptions();
// Set CompressImages option
optimizeOptions.ImageCompressionOptions.CompressImages = true;
// Set ImageQuality option
optimizeOptions.ImageCompressionOptions.ImageQuality = 75;
// Set Imagae Compression Version to fast
optimizeOptions.ImageCompressionOptions.Version = Pdf.Optimization.ImageCompressionVersion.Fast;
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "FastShrinkImages_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
Console.WriteLine("Ticks: {0}", DateTime.Now.Ticks - time);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open Document
Document doc = new Document(dataDir + "AddImage.pdf");
// Initialize OptimizationOptions
var optimizationOptions = new Aspose.Pdf.Optimization.OptimizationOptions();
// To optimise image using FlateDecode Compression set optimization options to Flate
optimizationOptions.ImageCompressionOptions.Encoding = ImageEncoding.Flate;
// Set Optimization Options
doc.OptimizeResources(optimizationOptions);
// Save Document
doc.Save(dataDir + "FlateDecodeCompression.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Load the source PDF file
Document doc = new Document(dataDir+ "ImageInformation.pdf");
// Define the default resolution for image
int defaultResolution = 72;
System.Collections.Stack graphicsState = new System.Collections.Stack();
// Define array list object which will hold image names
System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names);
// Insert an object to stack
graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));
// Get all the operators on first page of document
foreach (Operator op in doc.Pages[1].Contents)
{
// Use GSave/GRestore operators to revert the transformations back to previously set
Aspose.Pdf.Operators.GSave opSaveState = op as Aspose.Pdf.Operators.GSave;
Aspose.Pdf.Operators.GRestore opRestoreState = op as Aspose.Pdf.Operators.GRestore;
// Instantiate ConcatenateMatrix object as it defines current transformation matrix.
Aspose.Pdf.Operators.ConcatenateMatrix opCtm = op as Aspose.Pdf.Operators.ConcatenateMatrix;
// Create Do operator which draws objects from resources. It draws Form objects and Image objects
Aspose.Pdf.Operators.Do opDo = op as Aspose.Pdf.Operators.Do;
if (opSaveState != null)
{
// Save previous state and push current state to the top of the stack
graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
}
else if (opRestoreState != null)
{
// Throw away current state and restore previous one
graphicsState.Pop();
}
else if (opCtm != null)
{
System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
(float)opCtm.Matrix.A,
(float)opCtm.Matrix.B,
(float)opCtm.Matrix.C,
(float)opCtm.Matrix.D,
(float)opCtm.Matrix.E,
(float)opCtm.Matrix.F);
// Multiply current matrix with the state matrix
((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);
continue;
}
else if (opDo != null)
{
// In case this is an image drawing operator
if (imageNames.Contains(opDo.Name))
{
System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
// Create XImage object to hold images of first pdf page
XImage image = doc.Pages[1].Resources.Images[opDo.Name];
// Get image dimensions
double scaledWidth = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2));
double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2));
// Get Height and Width information of image
double originalWidth = image.Width;
double originalHeight = image.Height;
// Compute resolution based on above information
double resHorizontal = originalWidth * defaultResolution / scaledWidth;
double resVertical = originalHeight * defaultResolution / scaledHeight;
// Display Dimension and Resolution information of each image
Console.Out.WriteLine(
string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}",
opDo.Name, scaledWidth, scaledHeight, resHorizontal,
resVertical));
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Initialize Time
var time = DateTime.Now.Ticks;
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir + "ResizeImage.pdf");
// Initialize OptimizationOptions
var optimizeOptions = new Pdf.Optimization.OptimizationOptions();
// Set CompressImages option
optimizeOptions.ImageCompressionOptions.CompressImages = true;
// Set ImageQuality option
optimizeOptions.ImageCompressionOptions.ImageQuality = 75;
// Set ResizeImage option
optimizeOptions.ImageCompressionOptions.ResizeImages = true;
// Set MaxResolution option
optimizeOptions.ImageCompressionOptions.MaxResolution = 300;
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "ResizeImages_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Instantiate Document object
Document doc = new Document();
// add page to pages collection of PDF file
Aspose.Pdf.Page page = doc.Pages.Add();
// Create an image instance
Aspose.Pdf.Image img = new Aspose.Pdf.Image();
// Set Image Width and Height in Points
img.FixWidth = 100;
img.FixHeight = 100;
// Set image type as SVG
img.FileType = Aspose.Pdf.ImageFileType.Unknown;
// Path for source file
img.File = dataDir + "aspose-logo.jpg";
page.Paragraphs.Add(img);
//Set page properties
page.PageInfo.Width = 800;
page.PageInfo.Height = 800;
dataDir = dataDir + "SetImageSize_out.pdf";
// save resultant PDF file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir + "Shrinkimage.pdf");
// Initialize OptimizationOptions
var optimizeOptions = new Pdf.Optimization.OptimizationOptions();
// Set CompressImages option
optimizeOptions.ImageCompressionOptions.CompressImages = true;
// Set ImageQuality option
optimizeOptions.ImageCompressionOptions.ImageQuality = 50;
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "Shrinkimage_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Initialize Document
Aspose.Pdf.Document document = new Document();
document.Pages.Add();
Page page = document.Pages[1];
FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open);
page.Resources.Images.Add(imageStream, ImageFilterType.Flate);
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
page.Contents.Add(new GSave());
// Set coordinates
int lowerLeftX = 0;
int lowerLeftY = 0;
int upperRightX = 600;
int upperRightY = 600;
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[] {rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY});
// Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
page.Contents.Add(new ConcatenateMatrix(matrix));
page.Contents.Add(new Do(ximage.Name));
page.Contents.Add(new GRestore());
document.Save(dataDir + "FlateDecodeCompression.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Operators();
string imageFile = dataDir+ "aspose-logo.jpg";
string inFile = dataDir + "DrawXFormOnPage.pdf";
string outFile = dataDir + "blank-sample2_out.pdf";
using (Document doc = new Document(inFile))
{
OperatorCollection pageContents = doc.Pages[1].Contents;
// The sample demonstrates
// GSave/GRestore operators usage
// ContatenateMatrix operator usage to position xForm
// Do operator usage to draw xForm on page
// Wrap existing contents with GSave/GRestore operators pair
// this is to get initial graphics state at the and of existing contents
// otherwise there might remain some undesirable transformations at the end of existing operators chain
pageContents.Insert(1, new Aspose.Pdf.Operators.GSave());
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Add save graphics state operator to properly clear graphics state after new commands
pageContents.Add(new Aspose.Pdf.Operators.GSave());
#region create xForm
// Create xForm
XForm form = XForm.CreateNewForm(doc.Pages[1], doc);
doc.Pages[1].Resources.Forms.Add(form);
form.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Define image width and heigh
form.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(200, 0, 0, 200, 0, 0));
// Load image into stream
Stream imageStream = new FileStream(imageFile, FileMode.Open);
// Add image to Images collection of the XForm Resources
form.Resources.Images.Add(imageStream);
XImage ximage = form.Resources.Images[form.Resources.Images.Count];
// Using Do operator: this operator draws image
form.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
form.Contents.Add(new Aspose.Pdf.Operators.GRestore());
#endregion
pageContents.Add(new Aspose.Pdf.Operators.GSave());
// Place form to the x=100 y=500 coordinates
pageContents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 100, 500));
// Draw form with Do operator
pageContents.Add(new Aspose.Pdf.Operators.Do(form.Name));
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
pageContents.Add(new Aspose.Pdf.Operators.GSave());
// Place form to the x=100 y=300 coordinates
pageContents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 100, 300));
// Draw form with Do operator
pageContents.Add(new Aspose.Pdf.Operators.Do(form.Name));
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Restore grahics state with GRestore after the GSave
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
doc.Save(outFile);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Operators();
// Open document
Document pdfDocument = new Document(dataDir+ "PDFOperators.pdf");
// Set coordinates
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;
// Get the page where image needs to be added
Page page = pdfDocument.Pages[1];
// Load image into stream
FileStream imageStream = new FileStream(dataDir + "PDFOperators.jpg", FileMode.Open);
// Add image to Images collection of Page Resources
page.Resources.Images.Add(imageStream);
// Using GSave operator: this operator saves current graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Create Rectangle and Matrix objects
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });
// Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
// Using Do operator: this operator draws image
page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
// Using GRestore operator: this operator restores graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
dataDir = dataDir + "PDFOperators_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Operators();
Document doc = new Document(dataDir+ "RemoveGraphicsObjects.pdf");
Page page = doc.Pages[2];
OperatorCollection oc = page.Contents;
// Used path-painting operators
Operator[] operators = new Operator[] {
new Aspose.Pdf.Operators.Stroke(),
new Aspose.Pdf.Operators.ClosePathStroke(),
new Aspose.Pdf.Operators.Fill()
};
oc.Delete(operators);
doc.Save(dataDir+ "No_Graphics_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
string pbxFile = "";
string inFile = dataDir + @"DigitallySign.pdf";
string outFile = dataDir + @"DigitallySign_out.pdf";
using (Document document = new Document(inFile))
{
using (PdfFileSignature signature = new PdfFileSignature(document))
{
PKCS7 pkcs = new PKCS7(pbxFile, "WebSales"); // Use PKCS7/PKCS7Detached objects
DocMDPSignature docMdpSignature = new DocMDPSignature(pkcs, DocMDPAccessPermissions.FillingInForms);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100);
// Set signature appearance
signature.SignatureAppearance = dataDir + @"aspose-logo.jpg";
// Create any of the three signature types
signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature);
// Save output PDF file
signature.Save(outFile);
}
}
using (Document document = new Document(outFile))
{
using (PdfFileSignature signature = new PdfFileSignature(document))
{
IList<string> sigNames = signature.GetSignNames();
if (sigNames.Count > 0) // Any signatures?
{
if (signature.VerifySigned(sigNames[0] as string)) // Verify first one
{
if (signature.IsCertified) // Certified?
{
if (signature.GetAccessPermissions() == DocMDPAccessPermissions.FillingInForms) // Get access permission
{
// Do something
}
}
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
Document doc = new Document(dataDir + "blank.pdf");
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature())
{
pdfSign.BindPdf(doc);
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0]);
pdfSign.SignatureAppearance = dataDir + "demo.png";
pdfSign.Sign(1, "Reason", "Contact", "Location", true, new System.Drawing.Rectangle(100, 100, 200, 200), externalSignature);
pdfSign.Save(dataDir + "externalSignature2.pdf");
}
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature(new Document(dataDir + "externalSignature2.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
File.Copy(dataDir + "blank.pdf", dataDir + "externalSignature1.pdf", true);
using (FileStream fs = new FileStream(dataDir + "externalSignature1.pdf", FileMode.Open, FileAccess.ReadWrite))
{
using (Document doc = new Document(fs))
{
SignatureField field1 = new SignatureField(doc.Pages[1], new Rectangle(100, 400, 10, 10));
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0])
{
Authority = "Me",
Reason = "Reason",
ContactInfo = "Contact"
};
field1.PartialName = "sig1";
doc.Form.Add(field1, 1);
field1.Sign(externalSignature);
doc.Save();
}
}
using (PdfFileSignature pdfSign = new PdfFileSignature(new Document(dataDir + "externalSignature1.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
Document doc = new Document(dataDir + "input.pdf");
Stack graphicsState = new Stack();
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)doc.Pages[1].PageInfo.Width, (int)doc.Pages[1].PageInfo.Height);
System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
// Default ctm matrix value is 1,0,0,1,0,0
System.Drawing.Drawing2D.Matrix lastCTM = new System.Drawing.Drawing2D.Matrix(1, 0, 0, -1, 0, 0);
// System.Drawing coordinate system is top left based, while pdf coordinate system is low left based, so we have to apply the inversion matrix
System.Drawing.Drawing2D.Matrix inversionMatrix = new System.Drawing.Drawing2D.Matrix(1, 0, 0, -1, 0, (float)doc.Pages[1].PageInfo.Height);
System.Drawing.PointF lastPoint = new System.Drawing.PointF(0, 0);
System.Drawing.Color fillColor = System.Drawing.Color.FromArgb(0, 0, 0);
System.Drawing.Color strokeColor = System.Drawing.Color.FromArgb(0, 0, 0);
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bitmap))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));
// Process all the contents commands
foreach (Operator op in doc.Pages[1].Contents)
{
Aspose.Pdf.Operators.GSave opSaveState = op as Aspose.Pdf.Operators.GSave;
Aspose.Pdf.Operators.GRestore opRestoreState = op as Aspose.Pdf.Operators.GRestore;
Aspose.Pdf.Operators.ConcatenateMatrix opCtm = op as Aspose.Pdf.Operators.ConcatenateMatrix;
Aspose.Pdf.Operators.MoveTo opMoveTo = op as Aspose.Pdf.Operators.MoveTo;
Aspose.Pdf.Operators.LineTo opLineTo = op as Aspose.Pdf.Operators.LineTo;
Aspose.Pdf.Operators.Re opRe = op as Aspose.Pdf.Operators.Re;
Aspose.Pdf.Operators.EndPath opEndPath = op as Aspose.Pdf.Operators.EndPath;
Aspose.Pdf.Operators.Stroke opStroke = op as Aspose.Pdf.Operators.Stroke;
Aspose.Pdf.Operators.Fill opFill = op as Aspose.Pdf.Operators.Fill;
Aspose.Pdf.Operators.EOFill opEOFill = op as Aspose.Pdf.Operators.EOFill;
Aspose.Pdf.Operators.SetRGBColor opRGBFillColor = op as Aspose.Pdf.Operators.SetRGBColor;
Aspose.Pdf.Operators.SetRGBColorStroke opRGBStrokeColor = op as Aspose.Pdf.Operators.SetRGBColorStroke;
if (opSaveState != null)
{
// Save previous state and push current state to the top of the stack
graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
}
else if (opRestoreState != null)
{
// Throw away current state and restore previous one
graphicsState.Pop();
lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
}
else if (opCtm != null)
{
System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
(float)opCtm.Matrix.A,
(float)opCtm.Matrix.B,
(float)opCtm.Matrix.C,
(float)opCtm.Matrix.D,
(float)opCtm.Matrix.E,
(float)opCtm.Matrix.F);
// Multiply current matrix with the state matrix
((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);
lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
}
else if (opMoveTo != null)
{
lastPoint = new System.Drawing.PointF((float)opMoveTo.X, (float)opMoveTo.Y);
}
else if (opLineTo != null)
{
System.Drawing.PointF linePoint = new System.Drawing.PointF((float)opLineTo.X, (float)opLineTo.Y);
graphicsPath.AddLine(lastPoint, linePoint);
lastPoint = linePoint;
}
else if (opRe != null)
{
System.Drawing.RectangleF re = new System.Drawing.RectangleF((float)opRe.X, (float)opRe.Y, (float)opRe.Width, (float)opRe.Height);
graphicsPath.AddRectangle(re);
}
else if (opEndPath != null)
{
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
else if (opRGBFillColor != null)
{
fillColor = opRGBFillColor.getColor();
}
else if (opRGBStrokeColor != null)
{
strokeColor = opRGBStrokeColor.getColor();
}
else if (opStroke != null)
{
graphicsPath.Transform(lastCTM);
graphicsPath.Transform(inversionMatrix);
gr.DrawPath(new System.Drawing.Pen(strokeColor), graphicsPath);
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
else if (opFill != null)
{
graphicsPath.FillMode = FillMode.Winding;
graphicsPath.Transform(lastCTM);
graphicsPath.Transform(inversionMatrix);
gr.FillPath(new System.Drawing.SolidBrush(fillColor), graphicsPath);
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
else if (opEOFill != null)
{
graphicsPath.FillMode = FillMode.Alternate;
graphicsPath.Transform(lastCTM);
graphicsPath.Transform(inversionMatrix);
gr.FillPath(new System.Drawing.SolidBrush(fillColor), graphicsPath);
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
}
}
dataDir = dataDir + "ExtractBorder_out.png";
bitmap.Save(dataDir, ImageFormat.Png);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Create a new document
Document doc = new Document();
// Add page in document
Page page = doc.Pages.Add();
// Initialize new table
Table table = new Table
{
ColumnAdjustment = ColumnAdjustment.AutoFitToContent
};
// Add row in table
Row row = table.Rows.Add();
// Add cell in table
Cell cell = row.Cells.Add("Cell 1 text");
cell = row.Cells.Add("Cell 2 text");
// Get table width
Console.WriteLine(table.GetWidth());
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
DataTable dt = new DataTable("Employee");
dt.Columns.Add("data", System.Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr[0] = "<li>Department of Emergency Medicine: 3400 Spruce Street Ground Silverstein Bldg Philadelphia PA 19104-4206</li>";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "<li>Penn Observation Medicine Service: 3400 Spruce Street Ground Floor Donner Philadelphia PA 19104-4206</li>";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "<li>UPHS/Presbyterian - Dept. of Emergency Medicine: 51 N. 39th Street . Philadelphia PA 19104-2640</li>";
dt.Rows.Add(dr);
Document doc = new Document();
doc.Pages.Add();
// Initializes a new instance of the Table
Aspose.Pdf.Table tableProvider = new Aspose.Pdf.Table();
//Set column widths of the table
tableProvider.ColumnWidths = "400 50 ";
// Set the table border color as LightGray
tableProvider.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.5F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// Set the border for table cells
tableProvider.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.5F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
Aspose.Pdf.MarginInfo margin = new Aspose.Pdf.MarginInfo();
margin.Top = 2.5F;
margin.Left = 2.5F;
margin.Bottom = 1.0F;
tableProvider.DefaultCellPadding = margin;
tableProvider.ImportDataTable(dt, false, 0, 0, 3, 1, true);
doc.Pages[1].Paragraphs.Add(tableProvider);
doc.Save(dataDir + "HTMLInsideTableCell_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
// Load existing PDF document
Document pdfDocument = new Document(dataDir + "Table_input2.pdf");
// Create TableAbsorber object to find tables
TableAbsorber absorber = new TableAbsorber();
// Visit second page with absorber
absorber.Visit(pdfDocument.Pages[1]);
// Get copy of table collection
AbsorbedTable[] tables = new AbsorbedTable[absorber.TableList.Count];
absorber.TableList.CopyTo(tables, 0);
// Loop through the copy of collection and removing tables
foreach (AbsorbedTable table in tables)
absorber.Remove(table);
// Save document
pdfDocument.Save(dataDir + "Table2_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
// Load existing PDF document
Document pdfDocument = new Document(dataDir + "Table_input.pdf");
// Create TableAbsorber object to find tables
TableAbsorber absorber = new TableAbsorber();
// Visit first page with absorber
absorber.Visit(pdfDocument.Pages[1]);
// Get first table on the page
AbsorbedTable table = absorber.TableList[0];
// Remove the table
absorber.Remove(table);
// Save PDF
pdfDocument.Save(dataDir + "Table_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
// Load existing PDF document
Document pdfDocument = new Document(dataDir + @"Table_input2.pdf");
// Create TableAbsorber object to find tables
TableAbsorber absorber = new TableAbsorber();
// Visit first page with absorber
absorber.Visit(pdfDocument.Pages[1]);
// Get first table on the page
AbsorbedTable table = absorber.TableList[0];
// Create new table
Table newTable = new Table();
newTable.ColumnWidths = "100 100 100";
newTable.DefaultCellBorder = new BorderInfo(BorderSide.All, 1F);
Row row = newTable.Rows.Add();
row.Cells.Add("Col 1");
row.Cells.Add("Col 2");
row.Cells.Add("Col 3");
// Replace the table with new one
absorber.Replace(pdfDocument.Pages[1], table, newTable);
// Save document
pdfDocument.Save(dataDir + "TableReplaced_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// The path to the output document.
string outFile = dataDir + "AddHTMLOrderedListIntoDocuments_out.pdf";
// Instantiate Document object
Document doc = new Document();
// Instantiate HtmlFragment object with corresponding HTML fragment
HtmlFragment t = new HtmlFragment("`<body style='line-height: 100px;'><ul><li>First</li><li>Second</li><li>Third</li><li>Fourth</li><li>Fifth</li></ul>Text after the list.<br/>Next line<br/>Last line</body>`");
// Add Page in Pages Collection
Page page = doc.Pages.Add();
// Add HtmlFragment inside page
page.Paragraphs.Add(t);
// Save resultant PDF file
doc.Save(outFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Instantiate Document object
Document doc = new Document();
// Add a page to pages collection of PDF file
Page page = doc.Pages.Add();
// Instantiate HtmlFragment with HTML contnets
HtmlFragment titel = new HtmlFragment("<fontsize=10><b><i>Table</i></b></fontsize>");
// Set bottom margin information
titel.Margin.Bottom = 10;
// Set top margin information
titel.Margin.Top = 200;
// Add HTML Fragment to paragraphs collection of page
page.Paragraphs.Add(titel);
dataDir = dataDir + "AddHTMLUsingDOM_out.pdf";
// Save PDF file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document();
Page page = doc.Pages.Add();
HtmlFragment html = new HtmlFragment("<fontsize=10><b><i>Aspose.PDF</i></b></fontsize>");
page.Paragraphs.Add(html);
dataDir = dataDir + "HTMLfragmentRectangle_out.pdf";
doc.Save(dataDir);
Console.WriteLine(html.Rectangle.Width);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Instantiate Document object
Document doc = new Document();
// Add a page to pages collection of PDF file
Page page = doc.Pages.Add();
// Instantiate HtmlFragment with HTML contnets
HtmlFragment title = new HtmlFragment("<p style='font-family: Verdana'><b><i>Table contains text</i></b></p>");
//Font-family from 'Verdana' will be reset to 'Arial'
title.TextState = new TextState("Arial");
title.TextState.FontSize = 20;
// Set bottom margin information
title.Margin.Bottom = 10;
// Set top margin information
title.Margin.Top = 400;
// Add HTML Fragment to paragraphs collection of page
page.Paragraphs.Add(title);
// Save PDF file
dataDir = dataDir + "AddHTMLUsingDOMAndOverwrite_out.pdf";
// Save PDF file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
using (Document pdfDocument = new Document(dataDir + "text_sample4.pdf"))
{
TextFragmentAbsorber absorber = new TextFragmentAbsorber("Lorem ipsum");
pdfDocument.Pages.Accept(absorber);
TextFragment textFragment = absorber.TextFragments[1];
// Create new color with pattern colorspace
textFragment.TextState.ForegroundColor = new Aspose.Pdf.Color()
{
PatternColorSpace = new Aspose.Pdf.Drawing.GradientAxialShading(Color.Red, Color.Blue)
};
textFragment.TextState.Underline = true;
pdfDocument.Save(dataDir + "text_out.pdf");
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExtractParagraph()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document(dataDir + "input.pdf");
Page page = doc.Pages[2];
ParagraphAbsorber absorber = new ParagraphAbsorber();
absorber.Visit(page);
PageMarkup markup = absorber.PageMarkups[0];
foreach (MarkupSection section in markup.Sections)
{
DrawRectangleOnPage(section.Rectangle, page);
foreach (MarkupParagraph paragraph in section.Paragraphs)
{
DrawPolygonOnPage(paragraph.Points, page);
}
}
doc.Save(dataDir + "output_out.pdf");
}
private static void DrawRectangleOnPage(Rectangle rectangle, Page page)
{
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 0, 0));
page.Contents.Add(new Aspose.Pdf.Operators.SetRGBColorStroke(0, 1, 0));
page.Contents.Add(new Aspose.Pdf.Operators.SetLineWidth(2));
page.Contents.Add(
new Aspose.Pdf.Operators.Re(rectangle.LLX,
rectangle.LLY,
rectangle.Width,
rectangle.Height));
page.Contents.Add(new Aspose.Pdf.Operators.ClosePathStroke());
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
}
private static void DrawPolygonOnPage(Point[] polygon, Page page)
{
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 0, 0));
page.Contents.Add(new Aspose.Pdf.Operators.SetRGBColorStroke(0, 0, 1));
page.Contents.Add(new Aspose.Pdf.Operators.SetLineWidth(1));
page.Contents.Add(new Aspose.Pdf.Operators.MoveTo(polygon[0].X, polygon[0].Y));
for (int i = 1; i < polygon.Length; i++)
{
page.Contents.Add(new Aspose.Pdf.Operators.LineTo(polygon[i].X, polygon[i].Y));
}
page.Contents.Add(new Aspose.Pdf.Operators.LineTo(polygon[0].X, polygon[0].Y));
page.Contents.Add(new Aspose.Pdf.Operators.ClosePathStroke());
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf");
// Create TextAbsorber object to extract text
TextAbsorber textAbsorber = new TextAbsorber();
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(textAbsorber);
// Get the extracted text
string extractedText = textAbsorber.Text;
// Create a writer and open the file
TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt");
// Write a line of text to the file
tw.WriteLine(extractedText);
// Close the stream
tw.Close();
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf");
// Create TextAbsorber object to extract text
TextAbsorber absorber = new TextAbsorber();
absorber.TextSearchOptions.LimitToPageBounds = true;
absorber.TextSearchOptions.Rectangle = new Aspose.Pdf.Rectangle(100, 200, 250, 350);
// Accept the absorber for first page
pdfDocument.Pages[1].Accept(absorber);
// Get the extracted text
string extractedText = absorber.Text;
// Create a writer and open the file
TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt");
// Write a line of text to the file
tw.WriteLine(extractedText);
// Close the stream
tw.Close();
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ExtractTextPage.pdf");
// Create TextAbsorber object to extract text
TextAbsorber textAbsorber = new TextAbsorber();
// Accept the absorber for a particular page
pdfDocument.Pages[1].Accept(textAbsorber);
// Get the extracted text
string extractedText = textAbsorber.Text;
dataDir = dataDir + "extracted-text_out.txt";
// Create a writer and open the file
TextWriter tw = new StreamWriter(dataDir);
// Write a line of text to the file
tw.WriteLine(extractedText);
// Close the stream
tw.Close();
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document( dataDir + "input.pdf");
System.Text.StringBuilder builder = new System.Text.StringBuilder();
// String to hold extracted text
string extractedText = "";
foreach (Page pdfPage in pdfDocument.Pages)
{
using (MemoryStream textStream = new MemoryStream())
{
// Create text device
TextDevice textDevice = new TextDevice();
// Set text extraction options - set text extraction mode (Raw or Pure)
TextExtractionOptions textExtOptions = new
TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure);
textDevice.ExtractionOptions = textExtOptions;
// Convert a particular page and save text to the stream
textDevice.Process(pdfPage, textStream);
// Convert a particular page and save text to the stream
textDevice.Process(pdfDocument.Pages[1], textStream);
// Close memory stream
textStream.Close();
// Get text from memory stream
extractedText = Encoding.Unicode.GetString(textStream.ToArray());
}
builder.Append(extractedText);
}
dataDir = dataDir + "input_Text_Extracted_out.txt";
// Save the extracted text in text file
File.WriteAllText(dataDir, builder.ToString());
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Convert a particular page and save text to the stream
textDevice.Process(pdfDocument.Pages[1], textStream);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create GraphInfo object
Aspose.Pdf.GraphInfo graph = new Aspose.Pdf.GraphInfo();
// Set line width as 2
graph.LineWidth = 2;
// Set the color for graph object
graph.Color = Aspose.Pdf.Color.Red;
// Set dash array value as 3
graph.DashArray = new int[] { 3 };
// Set dash phase value as 1
graph.DashPhase = 1;
// Set footnote line style for page as graph
page.NoteLineStyle = graph;
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.FootNote = new Note("foot note for test text 1");
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
// Create second TextFragment
text = new TextFragment("Aspose.Pdf for .NET");
// Set FootNote for second text fragment
text.FootNote = new Note("foot note for test text 2");
// Add second text fragment to paragraphs collection of PDF file
page.Paragraphs.Add(text);
dataDir = dataDir + "AddFootNote_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document();
Page page = doc.Pages.Add();
TextFragment text = new TextFragment("some text");
page.Paragraphs.Add(text);
text.FootNote = new Note();
Aspose.Pdf.Image image = new Aspose.Pdf.Image();
image.File = dataDir + "aspose-logo.jpg";
image.FixHeight = 20;
text.FootNote.Paragraphs.Add(image);
TextFragment footNote = new TextFragment("footnote text");
footNote.TextState.FontSize = 20;
footNote.IsInLineParagraph = true;
text.FootNote.Paragraphs.Add(footNote);
Aspose.Pdf.Table table = new Aspose.Pdf.Table();
table.Rows.Add().Cells.Add().Paragraphs.Add(new TextFragment("Row 1 Cell 1"));
text.FootNote.Paragraphs.Add(table);
dataDir = dataDir + "AddImageAndTable_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.EndNote = new Note("sample End note");
// Specify custom label for FootNote
text.EndNote.Text = " Aspose(2015)";
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
dataDir = dataDir + "CreateEndNotes_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create GraphInfo object
Aspose.Pdf.GraphInfo graph = new Aspose.Pdf.GraphInfo();
// Set line width as 2
graph.LineWidth = 2;
// Set the color for graph object
graph.Color = Aspose.Pdf.Color.Red;
// Set dash array value as 3
graph.DashArray = new int[] { 3 };
// Set dash phase value as 1
graph.DashPhase = 1;
// Set footnote line style for page as graph
page.NoteLineStyle = graph;
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.FootNote = new Note("foot note for test text 1");
// Specify custom label for FootNote
text.FootNote.Text = " Aspose(2015)";
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
dataDir = dataDir + "CustomizeFootNoteLabel_out.pdf";
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create GraphInfo object
Aspose.Pdf.GraphInfo graph = new Aspose.Pdf.GraphInfo();
// Set line width as 2
graph.LineWidth = 2;
// Set the color for graph object
graph.Color = Aspose.Pdf.Color.Red;
// Set dash array value as 3
graph.DashArray = new int[] { 3 };
// Set dash phase value as 1
graph.DashPhase = 1;
// Set footnote line style for page as graph
page.NoteLineStyle = graph;
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.FootNote = new Note("foot note for test text 1");
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
// Create second TextFragment
text = new TextFragment("Aspose.Pdf for .NET");
// Set FootNote for second text fragment
text.FootNote = new Note("foot note for test text 2");
// Add second text fragment to paragraphs collection of PDF file
page.Paragraphs.Add(text);
dataDir = dataDir + "CustomLineStyleForFootNote_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
string outputFile = dataDir + "TextBlock_HideShow_MouseOverOut_out.pdf";
// Create sample document with text
Document doc = new Document();
doc.Pages.Add().Paragraphs.Add(new TextFragment("Move the mouse cursor here to display floating text"));
doc.Save(outputFile);
// Open document with text
Document document = new Document(outputFile);
// Create TextAbsorber object to find all the phrases matching the regular expression
TextFragmentAbsorber absorber = new TextFragmentAbsorber("Move the mouse cursor here to display floating text");
// Accept the absorber for the document pages
document.Pages.Accept(absorber);
// Get the first extracted text fragment
TextFragmentCollection textFragments = absorber.TextFragments;
TextFragment fragment = textFragments[1];
// Create hidden text field for floating text in the specified rectangle of the page
TextBoxField floatingField = new TextBoxField(fragment.Page, new Rectangle(100, 700, 220, 740));
// Set text to be displayed as field value
floatingField.Value = "This is the \"floating text field\".";
// We recommend to make field 'readonly' for this scenario
floatingField.ReadOnly = true;
// Set 'hidden' flag to make field invisible on document opening
floatingField.Flags |= AnnotationFlags.Hidden;
// Setting a unique field name isn't necessary but allowed
floatingField.PartialName = "FloatingField_1";
// Setting characteristics of field appearance isn't necessary but makes it better
floatingField.DefaultAppearance = new DefaultAppearance("Helv", 10, System.Drawing.Color.Blue);
floatingField.Characteristics.Background = System.Drawing.Color.LightBlue;
floatingField.Characteristics.Border = System.Drawing.Color.DarkBlue;
floatingField.Border = new Border(floatingField);
floatingField.Border.Width = 1;
floatingField.Multiline = true;
// Add text field to the document
document.Form.Add(floatingField);
// Create invisible button on text fragment position
ButtonField buttonField = new ButtonField(fragment.Page, fragment.Rectangle);
// Create new hide action for specified field (annotation) and invisibility flag.
// (You also may reffer floating field by the name if you specified it above.)
// Add actions on mouse enter/exit at the invisible button field
buttonField.Actions.OnEnter = new HideAction(floatingField, false);
buttonField.Actions.OnExit = new HideAction(floatingField);
// Add button field to the document
document.Form.Add(buttonField);
// Save document
document.Save(outputFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
int resolution = 150;
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "input.pdf");
using (MemoryStream ms = new MemoryStream())
{
PdfConverter conv = new PdfConverter(pdfDocument);
conv.Resolution = new Resolution(resolution, resolution);
conv.GetNextImage(ms, System.Drawing.Imaging.ImageFormat.Png);
Bitmap bmp = (Bitmap)Bitmap.FromStream(ms);
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp))
{
float scale = resolution / 72f;
gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height);
for (int i = 0; i < pdfDocument.Pages.Count; i++)
{
Page page = pdfDocument.Pages[1];
// Create TextAbsorber object to find all words
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+");
textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true;
page.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
if (i == 0)
{
gr.DrawRectangle(
Pens.Yellow,
(float)textFragment.Position.XIndent,
(float)textFragment.Position.YIndent,
(float)textFragment.Rectangle.Width,
(float)textFragment.Rectangle.Height);
for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++)
{
TextSegment segment = textFragment.Segments[segNum];
for (int charNum = 1; charNum <= segment.Characters.Count; charNum++)
{
CharInfo characterInfo = segment.Characters[charNum];
Aspose.Pdf.Rectangle rect = page.GetPageRect(true);
Console.WriteLine("TextFragment = " + textFragment.Text + " Page URY = " + rect.URY +
" TextFragment URY = " + textFragment.Rectangle.URY);
gr.DrawRectangle(
Pens.Black,
(float)characterInfo.Rectangle.LLX,
(float)characterInfo.Rectangle.LLY,
(float)characterInfo.Rectangle.Width,
(float)characterInfo.Rectangle.Height);
}
gr.DrawRectangle(
Pens.Green,
(float)segment.Rectangle.LLX,
(float)segment.Rectangle.LLY,
(float)segment.Rectangle.Width,
(float)segment.Rectangle.Height);
}
}
}
}
}
dataDir = dataDir + "HighlightCharacterInPDF_out.png";
bmp.Save(dataDir, System.Drawing.Imaging.ImageFormat.Png);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document(dataDir + "MultiColumnPdf.pdf");
ParagraphAbsorber absorber = new ParagraphAbsorber();
absorber.Visit(doc);
PageMarkup markup = absorber.PageMarkups[0];
Console.WriteLine("IsMulticolumnParagraphsAllowed == false\r\n");
MarkupSection section = markup.Sections[2];
MarkupParagraph paragraph = section.Paragraphs[section.Paragraphs.Count - 1];
Console.WriteLine("Section at {0} last paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
section = markup.Sections[1];
paragraph = section.Paragraphs[0];
Console.WriteLine("\r\nSection at {0} first paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
markup.IsMulticolumnParagraphsAllowed = true;
Console.WriteLine("\r\nIsMulticolumnParagraphsAllowed == true\r\n");
section = markup.Sections[2];
paragraph = section.Paragraphs[section.Paragraphs.Count - 1];
Console.WriteLine("Section at {0} last paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
section = markup.Sections[1];
paragraph = section.Paragraphs[0];
Console.WriteLine("\r\nSection at {0} first paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Instantiate document object
Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
// Create a page in the Pdf
Aspose.Pdf.Page page = doc.Pages.Add();
// Instantiate a table object
Aspose.Pdf.Table table1 = new Aspose.Pdf.Table();
// Add the table in paragraphs collection of the desired section
page.Paragraphs.Add(table1);
// Set with column widths of the table
table1.ColumnWidths = "120 270";
// Create MarginInfo object and set its left, bottom, right and top margins
Aspose.Pdf.MarginInfo margin = new Aspose.Pdf.MarginInfo();
margin.Top = 5f;
margin.Left = 5f;
margin.Right = 5f;
margin.Bottom = 5f;
// Set the default cell padding to the MarginInfo object
table1.DefaultCellPadding = margin;
// Create rows in the table and then cells in the rows
Aspose.Pdf.Row row1 = table1.Rows.Add();
// Create an image object
Aspose.Pdf.Image logo = new Aspose.Pdf.Image();
// Specify the image file path
logo.File = dataDir + "aspose-logo.jpg";
// Specify the image Fixed Height
logo.FixHeight = 120;
// Specify the image Fixed Width
logo.FixWidth = 110;
row1.Cells.Add();
// Add the image to paragraphs collection of the table cell
row1.Cells[0].Paragraphs.Add(logo);
// Create string variables with text containing html tags
string TitleString = "<font face=\"Arial\" size=6 color=\"#101090\"><b> Aspose.Pdf for .NET</b></font>";
string BodyString1 = "<font face=\"Arial\" size=2><br/>Aspose.Pdf for .NET is a non-graphical PDF� document reporting component that enables .NET applications to <b> create PDF documents from scratch </b> without utilizing Adobe Acrobat�. Aspose.Pdf for .NET is very affordably priced and offers a wealth of strong features including: compression, tables, graphs, images, hyperlinks, security and custom fonts. </font>";
// Create a text object to be added to the right of image
Aspose.Pdf.HtmlFragment TitleText = new Aspose.Pdf.HtmlFragment(TitleString + BodyString1);
row1.Cells.Add();
// Add the text paragraphs containing HTML text to the table cell
row1.Cells[1].Paragraphs.Add(TitleText);
// Set the vertical alignment of the row contents as Top
row1.Cells[1].VerticalAlignment = Aspose.Pdf.VerticalAlignment.Top;
// Create rows in the table and then cells in the rows
Aspose.Pdf.Row SecondRow = table1.Rows.Add();
SecondRow.Cells.Add();
// Set the row span value for Second row as 2
SecondRow.Cells[0].ColSpan = 2;
// Set the vertical alignment of the second row as Top
SecondRow.Cells[0].VerticalAlignment = Aspose.Pdf.VerticalAlignment.Top;
string SecondRowString = "<font face=\"Arial\" size=2>Aspose.Pdf for .NET supports the creation of PDF files through API and XML or XSL-FO templates. Aspose.Pdf for .NET is very easy to use and is provided with 14 fully featured demos written in both C# and Visual Basic.</font>";
Aspose.Pdf.HtmlFragment SecondRowText = new Aspose.Pdf.HtmlFragment(SecondRowString);
// Add the text paragraphs containing HTML text to the table cell
SecondRow.Cells[0].Paragraphs.Add(SecondRowText);
// Save the Pdf file
doc.Save(dataDir + "PlacingTextAroundImage_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Load source PDF file
Document doc = new Document(dataDir + "ExtractTextPage.pdf");
// Create TextFragment Absorber object with regular expression
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("[TextFragmentAbsorber,companyname,Textbox,50]");
doc.Pages.Accept(textFragmentAbsorber);
// Replace each TextFragment
foreach (TextFragment textFragment in textFragmentAbsorber.TextFragments)
{
// Set font of text fragment being replaced
textFragment.TextState.Font = FontRepository.FindFont("Arial");
// Set font size
textFragment.TextState.FontSize = 12;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Navy;
// Replace the text with larger string than placeholder
textFragment.Text = "This is a Larger String for the Testing of this issue";
}
dataDir = dataDir + "RearrangeContentsUsingTextReplacement_out.pdf";
// Save resultant PDF
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "RemoveAllText.pdf");
// Loop through all pages of PDF Document
for (int i = 1; i <= pdfDocument.Pages.Count; i++)
{
Page page = pdfDocument.Pages[i];
OperatorSelector operatorSelector = new OperatorSelector(new Aspose.Pdf.Operators.TextShowOperator());
// Select all text on the page
page.Contents.Accept(operatorSelector);
// Delete all text
page.Contents.Delete(operatorSelector.Selected);
}
// Save the document
pdfDocument.Save(dataDir + "RemoveAllText_out.pdf", Aspose.Pdf.SaveFormat.Pdf);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document