PDFsharp - Change page size and scale content - scale

Is it possible to scale a page from e.g. A2 to A1 with PDFsharp?
I can set the size of the page via Size, Width and Height. But how can I scale the content of the page?

based on the comment from Vive and the link provided there, here an example for resizing to A4 with C#:
you must include:
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp;
then:
// resize this file from A3 to A4
string filename = #"C:\temp\A3.pdf";
// Create the new output document (A4)
PdfDocument outputDocument = new PdfDocument();
outputDocument.PageLayout = PdfPageLayout.SinglePage;
XGraphics gfx;
XRect box;
// Open the file to resize
XPdfForm form = XPdfForm.FromFile(filename);
// Add a new page to the output document
PdfPage page = outputDocument.AddPage();
if (form.PixelWidth > form.PixelHeight)
page.Orientation = PageOrientation.Landscape;
else
page.Orientation = PageOrientation.Portrait;
double width = page.Width;
double height = page.Height;
gfx = XGraphics.FromPdfPage(page);
box = new XRect(0, 0, width, height);
gfx.DrawImage(form, box);
// Save the document...
string newfilename = #"c:\temp\resized.pdf";
outputDocument.Save(newfilename);

You can use DrawImage() to draw an existing PDF page on a new PDF page. You can specify the destination rectangle and thus you can scale the page as needed.
Use the XPdfForm class to access the existing PDF file.
See the Two Pages on One sample for details:
http://www.pdfsharp.net/wiki/TwoPagesOnOne-sample.ashx

Related

Drawing in MigraDoc document using XGraphics

I have generated some PDF report using MigraDoc. Initial code is as follows:-
MigraDoc.DocumentObjectModel.Document document = new MigraDoc.DocumentObjectModel.Document();
MigraDoc.DocumentObjectModel.Section section = document.AddSection();
...
Paragraph paragraph = section.Headers.Primary.AddParagraph();
....
table = section.AddTable();
...
paragraph = section.Footers.Primary.AddParagraph();
...
The PDF was rendered successfully. Now I want to add some graphics into the pages of this document. I have gone through several articles for that and found that everyone using PdfDocument class instead of MigraDoc.DocumentObjectModel.Document. Is it possible to apply graphics into pages of a document of type MigraDoc.DocumentObjectModel.Document using XGraphics? If it is not possible, what is the best way to mix PdfDocument with MigraDoc.DocumentObjectModel.Document to accomplish the same?
MigraDoc uses PDFsharp and an XGraphics object to create the PDF pages.
There are several ways to add content to pages created by MigraDoc.
This MigraDoc sample shows some options:
http://pdfsharp.net/wiki/MixMigraDocAndPdfSharp-sample.ashx
You can even call MigraDoc to use "your" XGraphics object for drawing:
// Alternative rendering with progress indicator.
// Set a callback for phase 1.
pdfRenderer.DocumentRenderer.PrepareDocumentProgress += PrepareDocumentProgress;
// Now start phase 1: Preparing pages (i.e. calculate the layout).
pdfRenderer.PrepareRenderPages();
// Now phase 2: create the PDF pages.
Console.WriteLine("\r\nRendering document ...");
int pages = pdfRenderer.DocumentRenderer.FormattedDocument.PageCount;
for (int i = 1; i <= pages; ++i)
{
var page = pdfRenderer.PdfDocument.AddPage();
Console.Write("\rRendering page " + i + "/" + pages);
PageInfo pageInfo = pdfRenderer.DocumentRenderer.FormattedDocument.GetPageInfo(i);
page.Width = pageInfo.Width;
page.Height = pageInfo.Height;
page.Orientation = pageInfo.Orientation;
using (XGraphics gfx = XGraphics.FromPdfPage(page))
{
gfx.MUH = pdfRenderer.Unicode ? PdfFontEncoding.Unicode : PdfFontEncoding.WinAnsi;
gfx.MFEH = pdfRenderer.FontEmbedding;
pdfRenderer.DocumentRenderer.RenderPage(gfx, i);
}
}
Console.WriteLine("\r\nSaving document ...");
Sample code taken from this post:
http://forum.pdfsharp.net/viewtopic.php?p=9293#p9293

PDFsharp set Width and Height of Page

I'm trying to set the page width and height to 4x6 in PDFsharp from C#. I'm using the following:
page.Width = "4in";
page.Height = "6in";
Still defaults a 8X11 page.
The following code worked for me:
PdfPage page = document.AddPage();
page.Width = "4in";
page.Height = "6in";
Using
pdfPage.Width = XUnit.FromInch(4);
pdfPage.Height = XUnit.FromInch(6);
is better because it avoids string parsing at runtime, but the string version is also working.
Was able to locate the answer to this here is the code to format the page to 4X6 inches:
pdfPage.Width = XUnit.FromInch(4);
pdfPage.Height = XUnit.FromInch(6);

Pdf Generation Using ITextSharp for Cheque Like Structure

I have requirement of online cheque generation.
I am using ,
using iTextSharp.text;
using iTextSharp.text.pdf;
I have dynamic cheque Height and width,font and fontsize.
And obviously cheque number with account information in all page of document.
My code goes like this
Document doc = new Document(new Rectangle(width, height), 0, 0, 0, 0);
string path = Server.MapPath("~/REPORTFILES");
var writer = PdfWriter.GetInstance(doc, new FileStream(path + "/cheque.pdf",FileMode.Create));
doc.Open();
BaseFont f_cn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
for (int i = fromchq; i <= tochq; i++)
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
cb.SetFontAndSize(f_cn, 14);
cb.SetFontAndSize(f_cn, fontsize);
cb.SetTextMatrix(cord_x, cord_y);
cb.ShowText(getProperty(propertyName,i.ToString().PadLeft(FromChqNo.Length, '0')));
cb.EndText();
doc.NewPage();
}
Here cord_x and cord_y is the co-ordinate location of that text.
Everything works fine i got pdf of my custom size.
like this :
But while printing it into the cheque
its work fine untill it has space enough to print single page. my xps image is attached bellow.
Area in red curve is skiped to be printed.
I mean to ask how can i make it posible that it will print serially, and completely fullfill my requirement that a cheque leaf of any height ,width,font will be printed serially. Thank you all in advance and also thanks for reading my problem.

Can PDFsharp automatically split a string over multiple pages?

I want to add the ability to generate a PDF of the content in my application (for simplicity, it will be text-only).
Is there any way to automatically work out how much content will fit in a single page, or to get any content that spills over one page to create a second (third, fourth, etc) page?
I can easily work it out for blocks of text - just split the text by a number of characters into a string array and then print each page in turn - but when the text has a lot of white space and character returns, this doesn't work.
Any advice?
Current code:
public void Generate(string title, string content, string filename)
{
PdfDocument document = new PdfDocument();
PdfPage page;
document.Info.Title = title;
XFont font = new XFont("Verdana", 10, XFontStyle.Regular);
List<String> splitText = new List<string>();
string textCopy = content;
int ptr = 0;
int maxCharacters = 3000;
while (textCopy.Length > 0)
{
//find a space in the text near the max character limit
int textLength = 0;
if (textCopy.Length > maxCharacters)
{
textLength = maxCharacters;
int spacePtr = textCopy.IndexOf(' ', textLength);
string startString = textCopy.Substring(ptr, spacePtr);
splitText.Add(startString);
int length = textCopy.Length - startString.Length;
textCopy = textCopy.Substring(spacePtr, length);
}
else
{
splitText.Add(textCopy);
textCopy = String.Empty;
}
}
foreach (string str in splitText)
{
page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(40, 100, 500, 600);
gfx.DrawRectangle(XBrushes.Transparent, rect);
tf.DrawString(str, font, XBrushes.Black, rect, XStringFormats.TopLeft);
}
document.Save(filename);
}
You can download PDFsharp together with MigraDoc. MigraDoc will automatically add pages as needed, you just create a document and add your text as paragraphs.
See MigraDoc samples page:
http://pdfsharp.net/wiki/MigraDocSamples.ashx
MigraDoc is the recommended way.
If you want to stick to PDFsharp, you can use the XTextFormatter class (source included with PDFsharp) to create a new class that also supports page breaks (e.g. by returning the count of chars that fit on the current page and have the calling code create a new page and call the formatter again with the remaining text).

Unable to Create Image of Special Characters

I have written a imageHandler.ashx in c# which draw image of a text on a fly . Its takes a parameter string txt. The Handler is called from Asp.net page. At the time of calling, if text contains the character # or any special character .it Does not create the images of #,or any special character's given to it.
According to my R&D the problem is with a Graphics.DrawString() method some how its is unable to write special characters.so please tell me how to create a image of a special characters
Code I am using :
String signatureText = HttpUtility.HtmlDecode(signatureText);
System.Drawing.Text.PrivateFontCollection fontCollection = new System.Drawing.Text.PrivateFontCollection();
FontFamily ff1 = fontCollection.Families[0];
// Initialize graphics
RectangleF rectF = new RectangleF(0, 0, imgWidth, imgHeight);
Bitmap pic = new Bitmap((int) rectF.Width,imgHeight, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(pic);
//g.SmoothingMode = SmoothingMode.Default;
// g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
Font font1 = new Font(ff1, imgHeight, FontStyle.Regular, GraphicsUnit.Pixel);
float bestFontSize = BestFontSize(g, new Size(imgWidth, imgHeight), font1, signatureText);
Font font2 = new Font(ff1, bestFontSize, FontStyle.Regular, GraphicsUnit.Pixel);
// Set colors
Color fontColor = Color.Black;
Color rectColor = Color.White;
SolidBrush fgBrush = new SolidBrush(fontColor);
SolidBrush bgBrush = new SolidBrush(rectColor);
// Rectangle or ellipse?
g.FillRectangle(bgBrush, rectF);
// Set font direction & alignment
StringFormat format = new StringFormat();
//format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
// Finally, draw the font
g.DrawString(signatureText, font2, fgBrush, rectF, format);
pic = (Bitmap) ImageUtility.ResizeImageWithAspectRatio(pic, imgWidth, imgHeight, true);
pic.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Any help is Appreciated Thanks in Advance
DrawString() don't have any problem while writing special characters if they are provided in font file (.ttf)
Problem can be in the following line
System.Drawing.Text.PrivateFontCollection fontCollection = new System.Drawing.Text.PrivateFontCollection();
Specially with the font you get in ff1
FontFamily ff1 = fontCollection.Families[0];
In your case it means Font ff1 don't have representation for some or all special characters.
Since I don't know how many font files you are getting from fontCollection.Families, if fontCollection.Families contain more than one font file try next one.
FontFamily ff1 = fontCollection.Families[1]; // and so on.
Or try to add font file with all special characters (if System.Drawing.Text.PrivateFontCollection is absolutely necessary ).
Alternatively you can use InstalledFontCollection instead of PrivateFontCollection
System.Drawing.Text.InstalledFontCollection fontCollection = new System.Drawing.Text.InstalledFontCollection();
Which will give you all installed fonts of the system on which application is running through its Families property InstalledFontCollection.
Easiest way is (if only one font is required, as you are using only one font in your provided code)
using constructor of FontFamily class with a string type parameter FontFamily.
Consider replacing this line
FontFamily ff1 = fontCollection.Families[0];
With this one
FontFamily fontFamily1 = new FontFamily("Arial");
Arial must be installed on the system where application is running.
Hope this will help.
DrawString doesn't have any problem with drawing special characters like # or copyright (I just tested it and produced the image below).
The problem might be from your URL parameter. Try encoding your text using Server.UrlEncode when passing the text, and then Server.UrlDecode before giving it to DrawString.

Resources