Automatic New Page based on text - c#

Hi there
i had been sucessfully using this great library PDF Sharp.now i wanted to play with some dynamic Stuff so people recomended to switch to Migradoc I did and like its paragraph feature.Now the problem is that when i add long paragraph then new page is not added instead of that there is incomplete text shown(incomplete in sense that text overflows) and i have added a image at the bottom for footer look.how can i do that i enter dynamic text (variable length ) and it just adds the required Number of pages.
My code so far is
XFont font = new XFont("Times New Roman", 12, XFontStyle.Bold);
XFont fontReg = new XFont("Times New Roman", 12, XFontStyle.Regular);
// HACKĀ²
gfx.MUH = PdfFontEncoding.Unicode;
gfx.MFEH = PdfFontEmbedding.Default;
string appPath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
XImage image = XImage.FromFile(appPath + "/header.png");
gfx.DrawImage(image, 0, 0);
//Civil Stamp
gfx.DrawImage(XImage.FromFile(appPath + "/cStamp.png"), 370, 380);
gfx.DrawImage(XImage.FromFile(appPath + "/Sp.png"), 230, 380);
CoverPageHeader();
Document doc = new Document();
MigraDoc.DocumentObjectModel.Section sec = doc.AddSection();
// Add a single paragraph with some text and format information.
MigraDoc.DocumentObjectModel.Paragraph para = sec.AddParagraph();
para.Format.Alignment = ParagraphAlignment.Left;
para.Format.Font.Name = "Times New Roman";
para.Format.Font.Size = 12;
para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black;
para.AddText("We are pleased to present the attached Document Please review the Agreement and, if acceptable, " +
"sign one copy and return it to us. We will sign the copy of the agreement and return one for " +
"your records.");
para.AddLineBreak();
para.AddLineBreak();
para.AddText(longlongtextString);
para.AddLineBreak();
para.AddLineBreak();
para.AddText("Sincerely,");
MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
// Render the paragraph. You can render tables or shapes the same way.
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(0.7), XUnit.FromCentimeter(9), "18cm", para);
gfx.DrawString("Kelly Turbin PhD., P.E.-SECB", font, XBrushes.Black, 20, 500);
gfx.DrawString("Principal", font, XBrushes.Black, 20, 520);
gfx.DrawString("Project No " + textBoxProjNumber.Text, fontReg, XBrushes.Black, 20,785);
gfx.DrawImage(XImage.FromFile(appPath + "/AccB.png"), 20, 700);
gfx.DrawImage(XImage.FromFile(appPath + "/ScreenMagic.png"), 100, 690);
gfx.DrawImage(XImage.FromFile(appPath + "/Footer.png"), 220, 750);
}

Don't use RenderObject, instead use RenderDocument and pages will be created automatically as needed.
Sample code here:
http://www.pdfsharp.net/wiki/HelloMigraDoc-sample.ashx

There is no way to automatically create new pages based on text size, when you are using the Mix of PDFSharp and MigraDoc, as it is in the question. The only solution is to use only MigraDoc with its RenderDocument method.

Related

PDFsharp: How to place next text after XTextFormatter?

I am using PDFsharp to create PDF documents. XTextFormatter is being used to wrap the text if it is going beyond specified y co-ordinate. However, I want to place "Phone number" just after the "tf.DrawString" text ends.
Currently, texts are getting overlapped as attached see here.
var dy = 13;
graphics.DrawString("Delivery Location: ", font, XBrushes.Black, new XPoint(20, 111));
graphics.DrawString(comp_name, font, XBrushes.Black, new XPoint(20, 111+ dy));
XRect rect = new XRect(20, 124, 200, 34);
graphics.DrawRectangle(XBrushes.SeaShell, rect);
tf.DrawString("This is just test. This is just test. This is just test. This is just test.",
font,
XBrushes.Black,
new XRect(rect.X + 5, rect.Y, rect.Width - 5, 34), XStringFormats.TopLeft);
graphics.DrawString("Phone Number: " + comp_phone1, font, XBrushes.Black, new XPoint(20, 136+ dy));
graphics.DrawString("GST: " + comp_gst, font, XBrushes.Black, new XPoint(20, 149+ dy));
graphics.DrawString("PAN: " + comp_pan, font, XBrushes.Black, new XPoint(20, 159+ dy));
The XTextFormatter is just a demo to get you started. Upgrade it according to your needs.
An upgraded version can be found here:
https://forum.pdfsharp.net/viewtopic.php?f=8&t=3192
This version returns the height needed for the text. You can add more text below.

Best way to change fonts in PDF document

At the moment I'm trying to change the fonts used in a PDF document.
I therefore declared rectangles and extract the text using LocationTextExtractionStrategy:
System.util.RectangleJ rect = new System.util.RectangleJ(fX, fY, fWidth, fHeight);
RenderFilter[] rfArea = { new RegionTextRenderFilter(rect) };
ITextExtractionStrategy str = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), rfArea);
string s = PdfTextExtractor.GetTextFromPage(reader, 1, str);
This works as expected, although it's quite complicated to find the right coordinates.
But how do I place the text in a new PDF document at the same starting location fX, fY so I don't break the layout?
I tried it using ColumnText but a multiline text is put one above the other:
Paragraph para = new Paragraph(fLineSpacing, s, font);
para.IndentationLeft = fLineIndentionLeft;
para.SpacingAfter = fSpacingAfter;
para.SpacingBefore = fSpacingBefore;
para.Alignment = iFontAlignment;
PdfContentByte cb = writer.DirectContent;
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(para, fX, fY + fHeight, fWidth + fX, fY, 0f, Element.ALIGN_LEFT);
ct.Go();
What am I missing? Or is there even something simpler? Using my approach I will have to cover the entire page defining lots of rectangles.

Custom page size in iTextSharp in C#.NET

I want to create a custom page size which is (5"X2") PDF using iTextSharp in C#. Is there any way to do this?
Document doc = new Document(iTextSharp.text.PageSize.A4, 15, 15, 0, 0);
Below code will demonstrate how to implement the custom PDF using PDF coordinates in C#.net. For this task you must aware about the pdf coordinates.
BaseFont f_cn;
string poath = Server.MapPath("~/fonts/CALIBRI.TTF");
f_cn = BaseFont.CreateFont(poath, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
using (System.IO.FileStream fs = new FileStream(Server.MapPath("~/TempPdf") + "\\" + "download.pdf", FileMode.Create))
{
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
Paragraph p = new Paragraph();
// Add meta information to the document
document.AddAuthor("Mikael Blomquist");
document.AddCreator("Sample application using iTestSharp");
document.AddKeywords("PDF tutorial education");
document.AddSubject("Document subject - Describing the steps creating a PDF document");
document.AddTitle("The document title - Amplified Resource Group");
// Open the document to enable you to write to the document
document.Open();
// Makes it possible to add text to a specific place in the document using
// a X & Y placement syntax.
PdfContentByte cb = writer.DirectContent;
cb.SetFontAndSize(f_cb, 16);
// First we must activate writing
cb.BeginText();
// Add an image to a fixed position from disk
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/arg.png"));
png.SetAbsolutePosition(200, 738);
cb.AddImage(png);
writeText(cb, "Header", 30, 718, f_cb, 14);
}
private void writeText(PdfContentByte cb, string Text, int X, int Y, BaseFont font, int Size)
{
cb.SetFontAndSize(font, Size);
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Text, X, Y, 0);
}
The document also accept the rectangle type, so we can create a rectangle of our custom size like below.
var pgSize = new iTextSharp.text.Rectangle(1000, 1000);
Document document = new Document(pgSize, 5f, 5f, 20f, 20f);

Create more than one Page with PDFSharp

hi im using PDFSharp for creating PDF-Document for some diagrams. after converting my diagrams in PDF, i should print them on one Page for very small Diagrams, but if i have big-Diagrams then printing them on one Page produce a bad Printing quality the diagram will be small displayed and the diagram content is not readable. if i give a high Scale, the diagram will be larger displayed but some of the nodes will disapear.
so how can i create more pages that depend on my Scale and Diagram-Size?
private void convertBitmap(BitmapSource Img)
{
try
{
PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();
document.Info.Title = activeDiagram.Model.Name;
PdfSharp.Pdf.PdfPage pdfPage = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(pdfPage);
XImage xIMage = XImage.FromBitmapSource(Img);
XImage logo = XImage.FromFile("logo.png");
pdfPage.Width = xIMage.PointWidth;
pdfPage.Height = xIMage.PointHeight;
//draw the logo
gfx.DrawImage(xIMage, 15, 70, pdfPage.Width, pdfPage.Height);
gfx.DrawImage(logo, 500, 5);
// Draw the texts
string typ = "";
if (activeDiagram == myDiagram1)
typ = "EPC";
XFont font = new XFont("Arial", 12, XFontStyle.Bold);
XFont font2 = new XFont("Arial", 10, XFontStyle.Bold);
gfx.DrawString("Modelname: " + activeDiagram.Model.Name, font, XBrushes.Black,
new XRect(50, 5, 400, 20), XStringFormats.TopLeft);
gfx.DrawString("Modeltyp: " + typ, font, XBrushes.Black, new XRect(50, 25, 400,
20), XStringFormats.TopLeft);
gfx.DrawLine(new XPen(XColor.FromKnownColor(XKnownColor.CornflowerBlue), 2), 20,
45, 600, 45);
gfx.DrawLine(new XPen(XColor.FromKnownColor(XKnownColor.CornflowerBlue), 2), 20,
900, 600, 900);
gfx.DrawString("Date: " + DateTime.Now.ToShortDateString(), font2, XBrushes.Black,
new XRect(50, 905, 100, 25), XStringFormats.TopLeft);
gfx.DrawString("Page: 1 von 1 ", font2, XBrushes.Black, new XRect(530, 905, 100,
25), XStringFormats.TopLeft);
SaveFileDialog dlg = new SaveFileDialog();
lg.FileName = activeDiagram.Model.Name;
dlg.AddExtension = true;
dlg.DefaultExt = "pdf";
dlg.Filter = "PDF Document|*.pdf|*.pdf|";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Save the document...
string filename = dlg.FileName;
document.Save(filename);
// ...and start a viewer.
Process.Start(filename);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "Error saving graph as a
pdf");
}
}
Creating multiple pages with PDFsharp is simple - but PDFsharp is not prepared to distribute your bitmap accross several pages, so this task is left to you.
Depending on the size of the bitmap, your code should decide to cut the image into two or four parts and draw them on two or four pages. This way you don't have to rely onto the capabilities of a printer driver.
PDFsharp can create larger pages - but then you'd have to rely onto the capabilities of the printer driver to print a single PDF page onto several physical pages. That may or may not work.
If you split the image yourself, you have full control of the PDF file that comes out. I'd recommend having the two or four segments printed with a common (overlapping) strip.

How do I add a link to a file in PdfSharp?

I can't seem to get PdfSharp to show a picture for this annotation. It doesn't have the PdfAnnotation.Icon property, so I can't set that.
XFont font = new XFont("Verdana", 10);
PdfPage page = wDoc.Parent.Page;
XGraphics gfx = wDoc.Parent.gfx;
XRect rec = gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(30, 60), new XSize(30, 30)));
PdfRectangle rect = new PdfRectangle(rec);
PdfLinkAnnotation link = PdfLinkAnnotation.CreateFileLink(rect, wDoc.FileLocation);
gfx.DrawString("These files were attached:", font, XBrushes.Black, 30, 50, XStringFormat.Default);
link.Rectangle = new PdfRectangle(rec);
page.Annotations.Add(link);
I've gotten it that far, and the annotation DOES exist, except it's a blank box! How do I go about making it say something, or even just show a picture?
You need to use page.AddWebLink(AREArect) and then add the text area with gfx.drawstring(AREArect)
sample code for Uri usage:
...
PdfDocument pdfDoc = PdfReader.Open(myUri.LocalPath, PdfDocumentOpenMode.Import);
PdfDocument pdfNewDoc = new PdfDocument();
for (int i = 0; i < pdfDoc.Pages.Count; i++)
{
PdfPage page = pdfNewDoc.AddPage(pdfDoc.Pages[i]);
XFont fontNormal = new XFont("Calibri", 10, XFontStyle.Regular);
XGraphics gfx = XGraphics.FromPdfPage(page);
var xrect = new XRect(240, 395, 300, 20);
var rect = gfx.Transformer.WorldToDefaultPage(xrect);
var pdfrect = new PdfRectangle(rect);
//file link
page.AddFileLink(pdfrect, myUri.LocalPath);
//web link
//page.AddWebLink(pdfrect, myUri.AbsoluteUri);
gfx.DrawString("MyFileName", fontNormal, XBrushes.Black, xrect, XStringFormats.TopLeft);
}
pdfNewDoc.Save(myDestinationUri.LocalPath + "MyNewPdfFile.pdf");
...
I am not familiar with class PdfLinkAnnotation.
You can use page.AddDocumentLink, page.AddWebLink, and page.AddFileLink to create links.
If you use these methods, you can draw the icon as an image.

Categories