Create more than one Page with PDFSharp - c#

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.

Related

Save an image and text as one

I am currently making an MVC project where the User will receive a Certificate which is displayed on the page. The Certificate is an image and then Text is used to overlap the image where the Users name and other information will be printed, using css to format the text to the correct part of the image.
As the image and text are technically still separate, saving the image does not save the text on top so what you save is just the template of a certificate and no text.
Is there a way to save both image and text as one, as if the text was pressed onto the image and was the same object? If so, I would appreciate being pointed in the right direction to know how to do this. Any ideas or code to save an image and text as one it would be very helpful.
Thanks.
May this help you
private void makeCertificate(string name, string id, string otherDetails) //You can pass any other details as well
{
System.Drawing.Image PrePrintedCertificate;
name = name.ToUpper();
string PrePrintedCertificateName = "Certificate.jpg"; //Assuming Certificate JPG File is in the bin folder
using (FileStream stream = new FileStream(PrePrintedCertificateName, FileMode.Open, FileAccess.Read))
{
PrePrintedCertificate = System.Drawing.Image.FromStream(stream);
}
RectangleF rectf4Name = new RectangleF(655, 460, 535, 90); //rectf for Name
RectangleF rectf4ID = new RectangleF(655, 560, 400, 40);
System.Drawing.Rectangle rect;
Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1241, 1756));
using (Graphics g = Graphics.FromImage(picEdit))
{
//g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red, 2), 662, 530, 90, 40);
//I have used upper line to see where is my RectangleF creating on the image
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
StringFormat sf1 = new StringFormat();
sf1.Alignment = StringAlignment.Near;
//g.DrawImage(codeImage, rect); //If you wanted to draw another image on the certificate image
g.DrawString(name, new System.Drawing.Font("Thaoma", 26, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, rectf4Name, sf);
g.DrawString(Track.Text, new System.Drawing.Font("Thaoma", 14, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, rectf4ID, sf1);
}
try
{
if (File.Exists(id + ".jpg"))
File.Delete(id + ".jpg");
picEdit.Save(id + ".jpg", ImageFormat.Jpeg);
picEdit.Dispose();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Things to note here is that this image is a A4 size paper image with portrait orientation. You probably need to change Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1241, 1756)); to Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1756,1241));
Another thing is the names and other details has been printed on the image with random place but you can see where exactly you wish to print the details.
You can look where it will get printed using g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red, 2), 662, 530, 90, 40); the Parameters you gonna pass here will be same as the RectangleF Parameters.
Save the graphic as an SVG and add the text using a text object.
You can also use CSS within the SVG to style the text.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text x="20" y="40">Example SVG text 1</text>
</svg>

PDF Sharp - Cannot edit certain pdfs

Using the following code, I am able to write page numbers to SOME files.
var outputDocument = new PdfDocument();
var currentPageNumber = 1;
var inputDocument = PdfReader.Open(#"C:\SamplePdfs\display.pdf", PdfDocumentOpenMode.Import);
for (var i = 0; i < inputDocument.PageCount; i++)
{
PdfPage page = outputDocument.AddPage(inputDocument.Pages[i]);
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Arial", 100, XFontStyle.Regular);
gfx.DrawString(Convert.ToString(currentPageNumber), font, XBrushes.Black, new XRect(0, 0, page.Width - 100, page.Height - 100), XStringFormats.BottomCenter);
currentPageNumber++;
}
outputDocument.Save(#"c:\test\sample1.pdf");
Why would I not be able to use that code to write to certain pdfs?
Update: I have found a pdf online that exhibits the same issue.
PDF
Update #2: Different host:
Dropbox
https://www.dropbox.com/s/0e0exs0lhytx3xl/ThirdConversion.pdf?dl=0
The file NewDisplay.pdf uses negative values in the MediaBox: MediaBox[-89.5 -702.5 702.5 -90.5]
Most PDF files use positive values. Maybe your page numbers will show up when you use negative values for x and y.

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);

Automatic New Page based on text

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.

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