Get original Size of PDF - c#

I want to get the same image quality as if I would use the export pdf to png from Adobe Acrobat.
But somehow this does not work for me. The dimensions that I get if I export the pdf to a png with help of the Adobe Acrobat tool are:
Width:11264 pix
Height:15940 pix
As you may see I provide you the method that I use to read the pdf an create per page a image. The possibilities that I have are to use the .Render Method which needs a int page(index) float dpiX, float dpiY, bool forPrinting
But some how it has no effect on the image saved ?
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
//This int is used to get the page count for each document
int pagecount = document.PageCount;
//With the int pagecount we can create as may screenshots as there are pages in the document
for (int index = 0; index < pagecount; index++)
{
//render the image created
var image = document.Render(index,8448,11955, true);
//savde the created screenshot temporerlay as a png + number (count)
image.Save(#"C:\Users\chnikos\Desktop\Test\output" + index.ToString("000") + ".png",ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\Test\output" + index.ToString("000") + ".png");
}
}

try
{
using (var document = PdfiumViewer.PdfDocument.Load(#"C:\Users\ohernandez\Pictures\img\descarga.pdf"))
{
for (int index = 0; index < document.PageCount; index++)
{
var image = document.Render(index, 300, 300, PdfRenderFlags.CorrectFromDpi);
image.Save(#"C:\Users\ohernandez\Pictures\img\output.Jpeg" + index.ToString("000") + ".Jpeg", ImageFormat.Jpeg);
}
}
}
catch (Exception ex)
{
// handle exception here;
}

This might be a better example:
Library files
using System.Drawing.Imaging;
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//This one is with Spire.Pdf
void PDF_To_Image(string pdf)
{
var doc = new Spire.Pdf.PdfDocument();
doc.LoadFromFile(pdf);
//This int is used to get the page count for each document
int pagecount = doc.Pages.Count;
//With the int pagecount we can create as many screenshots as there are pages in the document
for (int index = 0; index < pagecount; index++)
{
//render the image created
var dpiX = 75;
var dpiY = 75;
var image = doc.SaveAsImage(index, Spire.Pdf.Graphics.PdfImageType.Bitmap, dpiX, dpiY);
//save the created screenshot temporerlay as a png + number (count)
image.Save(Desktop + #"\Test\output\" + index.ToString("000") + ".png", ImageFormat.Png);
}
}
//This one is with Aspose.Pdf & xps2img.
//Aspose.Pdf converts the Pdf document to Xps format..
//xps2img creates images from the xps file..
void PDF_To_Image2(string pdf)
{
var doc = new Aspose.Pdf.Document(pdf);
var saveOptions = new Aspose.Pdf.XpsSaveOptions();
doc.Save("Preview.xps", saveOptions);
xps2img.Parameters pp = new xps2img.Parameters();
pp.Dpi = 300;
pp.ImageType = xps2img.ImageType.Png;
pp.RequiredSize = new System.Drawing.Size((int)doc.PageInfo.Width, (int)doc.PageInfo.Height);
pp.ImageOptions = xps2img.ImageOptions.Default;
var img3 = xps2img.Xps2Image.ToBitmap("Preview.xps", pp).ToList();
//This int is used to get the page count for each document
int pagecount = img3.Count;
//With the int pagecount we can create as many screenshots as there are pages in the document
for (int index = 0; index < pagecount; index++)
{
img3[index].Save(Desktop + #"\Test\Output\" + index.ToString("000") + ".png", ImageFormat.Png);
}
}

Use PDFSharp & Migradocs
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Create a font
XFont font = new XFont("Times", 25, XFontStyle.Bold);
PageSize[] pageSizes = (PageSize[])Enum.GetValues(typeof(PageSize));
foreach (PageSize pageSize in pageSizes)
{
if (pageSize == PageSize.Undefined)
continue;
// One page in Portrait...
PdfPage page = document.AddPage();
page.Size = pageSize;
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.DrawString(pageSize.ToString(), font, XBrushes.DarkRed,
new XRect(0, 0, page.Width, page.Height),
XStringFormat.Center);
// ... and one in Landscape orientation.
page = document.AddPage();
page.Size = pageSize;
page.Orientation = PageOrientation.Landscape;
gfx = XGraphics.FromPdfPage(page);
gfx.DrawString(pageSize.ToString() + " (landscape)", font,
XBrushes.DarkRed, new XRect(0, 0, page.Width, page.Height),
XStringFormat.Center);
}
// Save the document...
string filename = "PageSizes.pdf";
document.Save(filename);
// ...and start a viewer.
Process.Start(filename);

Related

Create a pdf from pdf with images and watermark

From a pdf, I want to make a new pdf that I 'll add a watermark and then make each page an image page.
Is this possible with itext?
I don't know how to convert it to images, but for the watermark, as said by Usama Kiyani in comments, you should consider using itextsharp which can be installed through nugget packages manager. I already used it to add a water mark to an existing pdf file.
Here's the code I used, it add a diagonal red watermark (which text is argument watermarkText) in the center of each page of an existing pdf file (sourceFile), then save this modified version at the given location (outputFile) :
public static void AddWatermarkTextC(string sourceFile, string outputFile, string watermarkText)
{
BaseFont tWatermarkFont = null;
float tWatermarkFontSize = 48F;
iTextSharp.text.BaseColor tWatermarkFontColor = null;
float tWatermarkFontOpacity = 0.3F;
float tWatermarkRotation = 45.0F;
tWatermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
tWatermarkFontColor = iTextSharp.text.BaseColor.RED;
AddWatermarkTextC(sourceFile, outputFile, watermarkText, tWatermarkFont, tWatermarkFontSize, tWatermarkFontColor, tWatermarkFontOpacity, tWatermarkRotation);
}
public static void AddWatermarkTextC(string sourceFile, string outputFile, string watermarkText, iTextSharp.text.pdf.BaseFont watermarkFont, float watermarkFontSize, iTextSharp.text.BaseColor watermarkFontColor, float watermarkFontOpacity, float watermarkRotation)
{
iTextSharp.text.pdf.PdfReader reader = null;
iTextSharp.text.pdf.PdfStamper stamper = null;
iTextSharp.text.pdf.PdfGState gstate = null;
iTextSharp.text.pdf.PdfContentByte underContent = null;
iTextSharp.text.Rectangle rect = null;
float currentY = 0.0F;
float offset = 0.0F;
int pageCount = 0;
try
{
reader = new iTextSharp.text.pdf.PdfReader(sourceFile);
rect = reader.GetPageSizeWithRotation(1);
FileStream stream = new System.IO.FileStream(outputFile, System.IO.FileMode.Create);
stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);
if (watermarkFont == null)
{
watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
}
if (watermarkFontColor == null)
{
watermarkFontColor = iTextSharp.text.BaseColor.RED;
}
gstate = new iTextSharp.text.pdf.PdfGState();
gstate.FillOpacity = watermarkFontOpacity;
gstate.StrokeOpacity = watermarkFontOpacity;
pageCount = reader.NumberOfPages;
for (int i = 1; i <= pageCount; i++)
{
underContent = stamper.GetOverContent(i);
underContent.SaveState();
underContent.SetGState(gstate);
underContent.SetColorFill(watermarkFontColor);
underContent.BeginText();
underContent.SetFontAndSize(watermarkFont, watermarkFontSize);
underContent.SetTextMatrix(30, 30);
currentY = (rect.Height / 2);
underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText, rect.Width / 2, currentY - offset, watermarkRotation);
underContent.EndText();
underContent.RestoreState();
}
stamper.Close();
reader.Close();
stream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
I guess it's not really hard to change it to fit your need, but if there's is anything you need me to explain just ask for it.

MigraDoc and PDFsharp showing different documents when saving as PDF and image

When saving, the image has the right design but the PDF has the wrong text on it. Could you explain why the documents are different?
I'm also open to other solutions for saving a PDF of the whole document and the ability to print a selected page of a multi-page document.
thanks :)
EDIT: the image is showing the date ("24th May 2016") which is correct and what I want the PDF to show, but instead the PDF is showing "TEST TEST"
1
public static void pdf() {
DateTime now = DateTime.Now;
string filename = "MixMigraDocAndPdfSharp.pdf";
filename = Guid.NewGuid().ToString("D").ToUpper() + ".pdf";
PdfDocument document = new PdfDocument();
SamplePage1(document);
document.Save(filename);
Process.Start(filename);
}
2
static void SamplePage1(PdfDocument document) {
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.MUH = PdfFontEncoding.Unicode;
gfx.MFEH = PdfFontEmbedding.Default;
XFont font = new XFont("Verdana", 13, XFontStyle.Bold);
gfx.DrawString("TEST TEST", font, XBrushes.Black,
new XRect(100, 100, page.Width - 200, 300), XStringFormats.Center);
Document doc = new Document();
Section sec = doc.AddSection();
Paragraph para = sec.AddParagraph();
header("24th May 2016");
DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", para);
PageInfo info = docRenderer.FormattedDocument.GetPageInfo(1);
int dpi = 150;
int dx, dy;
if (info.Orientation == PdfSharp.PageOrientation.Portrait) {
dx = (int)(info.Width.Inch * dpi);
dy = (int)(info.Height.Inch * dpi);
} else {
dx = (int)(info.Height.Inch * dpi);
dy = (int)(info.Width.Inch * dpi);
}
Image image = new Bitmap(dx, dy, PixelFormat.Format32bppRgb);
Graphics graphics = Graphics.FromImage(image);
graphics.Clear(System.Drawing.Color.White);
float scale = dpi / 72f;
graphics.ScaleTransform(scale, scale);
gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point));
docRenderer.RenderPage(gfx, 1);
gfx.Dispose();
image.Save("test.png", ImageFormat.Png);
doc.BindToRenderer(docRenderer);
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", para);
Process.Start("mspaint", "test.png");
}
3
public static void header(String date) {
Paragraph paragraph = new Paragraph();
var dateIssued = firstPage.AddTextFrame();
dateIssued.Height = "1.0cm";
dateIssued.Width = "6.0cm";
dateIssued.Left = "2.1cm";
dateIssued.RelativeHorizontal = RelativeHorizontal.Margin;
dateIssued.Top = "3.55cm";
dateIssued.RelativeVertical = RelativeVertical.Page;
paragraph = dateIssued.AddParagraph(date);
}
You call docRenderer.RenderPage(gfx, 1); for the image only. This renders the header.
You do not call docRenderer.RenderPage(gfx, 1); for the PDF. So no date there, just the "TEST TEST" you draw earlier.

How to maintain cropped information in pdf page after page extraction with itextsharp?

I am using acrobat 8.0 professional for cropping text from a PDF.
One page of Original pdf is
After cropping pdf above page is
In mine project i am using cropped pdf and extract individual pages from it by following code
private void ExtractPages(string inputFile, string outputFile, int start, int end)
{
// get input document
PdfReader inputPdf = new PdfReader(inputFile);
// retrieve the total number of pages
int pageCount = inputPdf.NumberOfPages;
if (end < start || end > pageCount)
{
end = pageCount;
}
//var pgSize = new iTextSharp.text.Rectangle(myWidth, myHeight);
//var doc = new iTextSharp.text.Document(pgSize, leftMargin, rightMargin, topMargin, bottomMargin);
// load the input document
Document inputDoc = new Document(inputPdf.GetPageSizeWithRotation(1));
// create the filestream
using (FileStream fs = new FileStream(outputFile, FileMode.Create))
{
// create the output writer
PdfWriter outputWriter = PdfWriter.GetInstance(inputDoc, fs);
inputDoc.Open();
PdfContentByte cb1 = outputWriter.DirectContent;
// copy pages from input to output document
for (int i = start; i <= end; i++)
{
inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(i));
inputDoc.NewPage();
PdfImportedPage page = outputWriter.GetImportedPage(inputPdf, i);
int rotation = inputPdf.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb1.AddTemplate(page, 0, -1f, 1f, 0, 0, inputPdf.GetPageSizeWithRotation(i).Height);
}
else
{
cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
inputDoc.Close();
}
}
Problem is that after page extraction cropping information is not retained in extracted pdf. Extracted pdf is same as original pdf with extra text in it.
How to retained cropped information in extracted pdf ?

Process Cannot Access the file "\Path" because it is being used by some other process

In my Project I am accessing a file local file and copying it to another file then watermarking it, but while copying I am getting the IO Exception “Can’t Access the file” I am sure that the file is free and not accessed by any other process can any body tell me what would be the problem is
My code is,
protected void AddWaterMark(string file)
{
string watermark = "Confidential Document Printed on " + DateTime.Now.ToString();
const int emSize = 40;
try
{
// Get a fresh copy of the sample PDF file
string filename = #"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\FileUpload\"+file;
string filename1 =#"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\FileUpload\" + file; ;
bool b = true;// File_lock(filename);
if(b==true)
{
File.Copy(Path.Combine(#"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\FileUpload",
filename), Path.Combine(#"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\UFileUpload ",
filename1), true); //Exception was Thrown Here
// Create the font for drawing the watermark
XFont font = new XFont("Times New Roman", emSize, XFontStyle.BoldItalic);
// Open an existing document for editing and loop through its pages
PdfDocument document = PdfReader.Open(filename);
// Set version to PDF 1.4 (Acrobat 5) because we use transparency.
if (document.Version < 14)
document.Version = 14;
for (int idx = 0; idx < document.Pages.Count; idx++)
{
//if (idx == 1) break;
PdfPage page = document.Pages[idx];
// Variation 1: Draw watermark as text string
// Get an XGraphics object for drawing beneath the existing content
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
// Get the size (in point) of the text
XSize size = gfx.MeasureString(watermark, font);
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(page.Width / 2, page.Height / 2);
gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);
// Create a string format
XStringFormat format = new XStringFormat();
format.Alignment = XStringAlignment.Near;
format.LineAlignment = XLineAlignment.Near;
// Create a dimmed red brush
XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
// Draw the string
gfx.DrawString(watermark, font, brush,
new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),format);
}
// Save the document...
document.Save(filename);
// ...and start a viewer
Process.Start(filename);
File.Exists(filename);
}
}
catch(Exception ex)
{
ClientMessaging(ex.Message);
}
}.
The problem is that you are trying to copy the file to itself and trying to override the file in the process
File.Copy("TextFile1.txt", "TextFile1.txt", true); //throws the error: "The process cannot access the file 'TextFile1.txt' because it is being used by another process."
File.Copy("TextFile1.txt", "TextFile2.txt", true); //copies the file
I've been there before, maybe you could try to do this :
public bool FileIsLocked(string strFullFileName)
{
bool blnReturn = false;
System.IO.FileStream fs = null;
try {
fs = System.IO.File.Open(strFullFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.None);
fs.Close();
} catch (System.IO.IOException ex) {
blnReturn = true;
}
return blnReturn;
}

PDFSharp Insert an image in a pdf using a PdfTextField as the position and size reference

We want to insert a png image with a (drawn)signature into a PDF with PDFSharp. The position and size of the image is determined by a invisible PdfTextField that we created previously in the PDF. With our current code the problem is: How can we get the page reference from our PdfTextField (the page that contains this field)?
Code:
PdfDocument document = PdfReader.Open("C:\\filex.pdf", PdfDocumentOpenMode.Modify);
// Get the root object of all interactive form fields
PdfAcroForm form = document.AcroForm;
// Get all form fields of the whole document
PdfAcroField.PdfAcroFieldCollection fields = form.Fields;
//Get the invisible PdfTextField used as position and size reference
PdfTextField signatureposition= (PdfTextField)fields["thesignature"];
PdfArray signaturerect= (PdfArray)signatureposition.Elements["/Rect"];
string x = signaturerect.Elements[0].ToString();
string y = signaturerect.Elements[1].ToString();
string w = signaturerect.Elements[2].ToString();
string h = signaturerect.Elements[3].ToString();
string imagepath= "C:\\signature.png";
//how to get the correct page reference respect the especified field?
PdfPage page= signatureposition.Owner.Pages[???];
XGraphics gfx = XGraphics.FromPdfPage(page);
XImage image = XImage.FromFile(imagepath);
gfx.DrawImage(image, x, y, width, height);
In the end we solved it creating this function:
protected int PaginaCampo(string campofirma, PdfDocument document)
{
for (int i = 0; i < document.Pages.Count; i++)
{
PdfAnnotations anotations = document.Pages[i].Annotations;
for (int j = 0; j < anotations.Count; j++)
{
if (anotations[j].Title != campofirma) continue;
return i;
}
}
return -1;
}
Not the best solution but it works...if someone adds a better one we will give the correct answer to him/her

Categories