Best way to change fonts in PDF document - c#

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.

Related

Rotate multiline text with Columntext ITextSharp

How do i rotate multiline text in itextsahrp?
I have tried:
float x = 200;
float y = 100;
PdfContentByte cb = stamper.GetOverContent(i);
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(new Phrase(new Chunk("Test \n new", FontFactory.GetFont(FontFactory.HELVETICA, 18, iTextSharp.text.Font.NORMAL))),
x, reader.GetCropBox(i).Height -( y+400),500+x, y, 10, Element.ALIGN_LEFT | Element.ALIGN_TOP);
ct.Go();
ColumnText.ShowTextAligned(
cb, Element.ALIGN_CENTER,
new Phrase(new Chunk("Test \n new", FontFactory.GetFont(FontFactory.HELVETICA, 18, iTextSharp.text.Font.NORMAL))), x, reader.GetCropBox(i).Height-y, 12);
ct.SetSimpleColumn shows multilie text but how do I rotate it?
ColumnText.ShowTextAligned does not show multiline.
I don't have a C# environment on my machines, so I've written an example in Java, named AddRotatedTemplate. I have taken an existing PDF file with the words "Hello World", I've created a template/XObject with some text, and I've added that template/XObject twice using the addTemplate() method (once using only x, y coordinates and once using parameters that rotate the text with PI / 4 grades). As a result, the text added to the template is added twice; see hello_template.pdf).
This is the code:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
// Get canvas for page 1
PdfContentByte cb = stamper.getOverContent(1);
// Create template (aka XOBject)
PdfTemplate xobject = cb.createTemplate(80, 120);
// Add content using ColumnText
ColumnText column = new ColumnText(xobject);
column.setSimpleColumn(new Rectangle(80, 120));
column.addElement(new Paragraph("Some long text that needs to be distributed over several lines."));
column.go();
// Add the template to the canvas
cb.addTemplate(xobject, 36, 600);
double angle = Math.PI / 4;
cb.addTemplate(xobject,
(float)Math.cos(angle), -(float)Math.sin(angle),
(float)Math.cos(angle), (float)Math.sin(angle),
150, 600);
stamper.close();
reader.close();
}
There may be easier ways to define the rotation in other variations of the addTemplate() method, but I'm an engineer and I am so used to using the transformation matrix that I never feel the need or desire to use any other type of method.

Using iTextSharp, is there a way to keep text from staying in a rectangle

I have an existing PDF (not with form fields - more of a scanned document), and am using PdfReader to load the PDF "template" so that I write text on it.
For position simple fields I am using:
PdfReader reader = new PdfReader(templatePath);
Chunk chunk = new Chunk(text, fontToUse);
Phrase phrase = new Phrase();
phrase.Add(chunk);
PdfContentByte canvas = this.PdfWriter.DirectContent;
ColumnText.ShowTextAligned(this.PdfContentByte, alignment, phrase, left, top, 0);
I also need to write some text to a specific area which is a 400 x 200 rectangle. Since the size of the text varies, it may or may not fit into the rectangle.
Is there a way to write text to the rectangle, and if the text is too large for it to simply not appear (like overflow hidden would work in HTML)?
Got it!
Phrase myText = new Phrase(text);
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 300;
table.LockedWidth = true;
PdfPCell cell = new PdfPCell(myText);
cell.Border = 0;
cell.FixedHeight = 40;
table.AddCell(cell);
table.WriteSelectedRows
(
0,
-1,
300,
700,
writer.DirectContent
);

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

itextsharp pdf page border?

I am using itext sharp for creating reports in PDF format.
I want page borders. I tried some ways. I am not successful.
How can I get a page border for top, bottom, left, right using iText for .NET?
I added one image 1. I want borders like described in the image.
You can try this code for adding the image for the header manually.
//Step 1: Add the Image file
strImgPath is refer the directory Info..
Image imgLogo = Image.GetInstance(strImgPath.ToString()+"\\abcdur compe.Jpg");
imgLogo.Alignment = Image.ALIGN_CENTER;
imgLogo.ScalePercent(50f);
// Step 2:
Add this ImgLogo to the PdfPTable by use of this
PdfPCell pdfcellImage = new PdfPCell(imgLogo, true);
pdfcellImage.FixedHeight = 40f;
pdfcellImage.HorizontalAlignment = Element.ALIGN_CENTER;
pdfcellImage.VerticalAlignment = Element.ALIGN_CENTER;
pdfcellImage.Border = Rectangle.NO_BORDER;
pdfcellImage.Border = Rectangle.NO_BORDER;
pdftblImage.AddCell(pdfcellImage);
// Step 3:
Create Chunck to add Text for address or others
fntBoldComHd is a Base Font Library Object
Chunk chnCompany = new Chunk("Your CompanyName\nAddress", fntBoldComHd);
//Step 4:
Create Phrase For add the Chunks and PdfPTables
Phrase phHeader = new Phrase();
phHeader.Add(pdftblImage);
phHeader.Add(chnCompany);
// Step 5:
Assign the Phrase to PDF Header
HeaderFooter header = new HeaderFooter(phHeader, false);
header.Border = Rectangle.NO_BORDER;
header.Alignment = Element.ALIGN_CENTER;
docPDF.Header = header;
I am using one hacky way of workaround but it will create the border.Use this method.
private void CreateBorder(PdfContentByte cb, PdfWriter writer, Document doc)
{
iTextSharp.text.Rectangle r = doc.PageSize;
float left = r.Left + 30;
float right = r.Right - 30;
float top = r.Top - 30;
float bottom = r.Bottom + 30;
float width = right - left;
float height = top - bottom;
PdfPTable tab = new PdfPTable(1);
tab.TotalWidth = width;
tab.LockedWidth = true;
PdfPCell t = new PdfPCell(new Phrase(String.Empty));
t.BackgroundColor = new BaseColor(250, 235, 215);
t.FixedHeight = height;
t.BorderWidth = 3;
tab.AddCell(t);
Paragraph pa = new Paragraph();
pa.Add(tab);
float h = tab.TotalHeight;
PdfTemplate temp = cb.CreateTemplate(tab.TotalWidth, h);
tab.WriteSelectedRows(0, -1, 0.0F, h, temp);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(temp);
img.SetAbsolutePosition(30, 30);
cb.AddImage(img);
}
If u want one more section for header create table width two rows.I hope this helps.
Are you referring to the document margins? If yes, use the Document object's ctor to specify them:
public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom);

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.

Categories