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.
Related
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.
I'm using iTextSharp to handle pdf files. I'd like to know how I can split a page in half and make 2 different pages from the two pieces. I tried a lot but nothing seems to work right now.
First try
iTextSharp.text.Rectangle size = new iTextSharp.text.Rectangle(0, pdfReader.GetPageSize(1).Height / 2, pdfReader.GetPageSize(1).Width, 0);
Second try
iTextSharp.text.Rectangle size = pdfReader.GetPageSizeWithRotation(1);
iTextSharp.text.Document document = new iTextSharp.text.Document(size.GetRectangle(0, size.Height / 2));
And several others. The results are always the same: I have a file with just the second half of the original page.
I don't understand your code snippets, but then again: probably you don't understand them either, so let's not look at what you've written so far, and let's take a closer look at the TileInTwo example:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
// Creating a reader
PdfReader reader = new PdfReader(src);
int n = reader.getNumberOfPages();
// step 1
Rectangle mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(1)));
Document document = new Document(mediabox);
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3
document.open();
// step 4
PdfContentByte content = writer.getDirectContent();
PdfImportedPage page;
int i = 1;
while (true) {
page = writer.getImportedPage(reader, i);
content.addTemplate(page, 0, -mediabox.getHeight());
document.newPage();
content.addTemplate(page, 0, 0);
if (++i > n)
break;
mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(i)));
document.setPageSize(mediabox);
document.newPage();
}
// step 5
document.close();
reader.close();
}
public Rectangle getHalfPageSize(Rectangle pagesize) {
float width = pagesize.getWidth();
float height = pagesize.getHeight();
return new Rectangle(width, height / 2);
}
In this example, we ask the PdfReader instance for the page size of the first page and we create a new rectangle with the same width and only half the height.
We then import each page in the document, and we add it twice on different pages:
once on the odd pages with a negative y value to show the upper half of the original page,
once on the even pages with y = 0 to show the lower half of the original page.
As every page in the original document can have a different size, we may need to change the page size for every new couple of pages.
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.
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.
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.