itext 7 - canvas with customized page - itext

In iText 2 , we can use PdfContentByte to set customized page-size, however, in iText 7.1.2.
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfPage page = pdf.addNewPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(0, 0, 2000, 800);
pdfCanvas.rectangle(rectangle);
pdfCanvas.stroke();
Canvas canvas = new Canvas(pdfCanvas, pdf, rectangle);
PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(FontConstants.TIMES_BOLD);
Text title =
new Text("The Strange Case of Dr. Jekyll and Mr. Hyde").setFont(bold);
Text author = new Text("Robert Louis Stevenson").setFont(font);
Paragraph p = new Paragraph().add(title).add(" by ").add(author);
canvas.add(p);
canvas.close();
pdf.close();
even if we set larger width, it didn't work. still keep A4 size. How can i change the pageSize correctly ?

You are adding a new page without specifying a page size, hence the default page size (A4) is used. Please take a look at the API docs for the addPage() method: addNewPage(PageSize pageSize). You need to pass a PageSize argument if you want to get a page with another size.
There's also a setDefaultPageSize() method if you want to change the default page size from A4 to something else.
The PageSize class extends the Rectangle class: http://itextsupport.com/apidocs/iText7/latest/com/itextpdf/kernel/geom/PageSize.html

Related

How can I take text and convert to PDF with landscape orientation and two text columns?

I need to change the paper orientation, and then divide the text into two columns. I want like it:
I come from a large text file and I need to add all of this text in the PDF as in the photo.
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
PageSize ps = PageSize.A4;;
Document doc = new Document(pdfDoc, ps);
BufferedReader br = new BufferedReader(new FileReader("verybigfileWithText.txt"));
while ((line = br.readLine()) != null) {
//split pdf and add text in two column without overlapping page
}
doc.close();
And I need to be able to change margin in center(between two columns) and margin top/right/bot/left. And get width every columns :)
Help me please
Pdf:
https://dropmefiles.com/HqD6f
To change the orientation of the page you can use PageSize#rotate, e.g. PageSize.A4.rotate()
To put content into two (or more) columns, you can create your own document renderer, or use an existing ColumnDocumentRenderer which suits your needs. It accepts column areas which allows you to control margins (or even position columns in a peculiar way which is probably not your use case):
Document document = new Document(pdfDocument, PageSize.A4.rotate());
Rectangle[] columnAreas = new Rectangle[] {new Rectangle(30, 30, 350, 520), new Rectangle(430, 30, 350, 520)};
ColumnDocumentRenderer renderer = new ColumnDocumentRenderer(document, columnAreas);
document.setRenderer(renderer);
document.add(new Paragraph(text).setTextAlignment(TextAlignment.JUSTIFIED));
document.close();
The result looks like this:

positioning text using itextSharp in C3

I am trying to generate a pdf on button click. I am having challenge to design the page. If anybody can help on, how to position the text in particular position.
Say I want my address to in the top right corner and heading in the center.
Here is the code I am working on:
private void pdf_btn_Click(object sender, EventArgs e)
{
SaveFileDialog svg = new SaveFileDialog();
svg.ShowDialog();
using (FileStream stream = new FileStream(svg.FileName + ".pdf", FileMode.Create))
{
// Create a Document object
var document = new Document(PageSize.A4, 50, 50, 25, 25);
// Create a new PdfWrite object, writing the output to a MemoryStream
// var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, stream);
document.Open();
// First, create our fonts... (For more on working w/fonts in iTextSharp, see: http://www.mikesdotnetting.com/Article/81/iTextSharp-Working-with-Fonts
var titleFont = FontFactory.GetFont("Arial", 18, Convert.ToInt32(Font.Bold));
var AddressFont = FontFactory.GetFont("Arial", 7, Convert.ToInt32(Font.Bold));
var boldTableFont = FontFactory.GetFont("Arial", 12, Convert.ToInt32(Font.Bold));
var endingMessageFont = FontFactory.GetFont("Arial", 10, Convert.ToInt32(Font.Italic));
var bodyFont = FontFactory.GetFont("Arial", 12);
// Add the "" title
document.Add(new Paragraph("Certificate of Analysis", titleFont));
// Add Address
var text = document.Add(new Paragraph("Abc Company", AddressFont));
document.Add(new Paragraph("Tel:(xx) xxx-xxxx, (xxx) xxx-xxx", AddressFont));
document.Add(new Paragraph("Fax: (xxx) xxx-xxx, , AddressFont));
document.Close();
stream.Close();
}
}
There are different ways to achieve what you want.
Currently, you are telling iText to do the layout. If you want to center the text "Certificate of Analysis", then you could change the alignment of the Paragraph like this:
Paragraph header = new Paragraph("Certificate of Analysis", titleFont);
header.Alignment = Element.ALIGN_CENTER;
document.Add(header);
If you want the text "Abc Company" to be right-aligned, you can change he alignment like this:
Paragraph company = new Paragraph("Abc Company", AddressFont);
company.Alignment = Element.ALIGN_RIGHT;
document.Add(company);
Of course: when we add company, it will start on a new line under header. Maybe you want the text to be on the same line.
In that case, why not use a PdfPTable?
PdfPTable myTable = new PdfPTable(3);
myTable.WidthPercentage = 100;
PdfPCell mydate = new PdfPCell(new Phrase("April 22, 2015", myfont));
mydate.Border = Rectangle.NO_BORDER;
myTable.AddCell(mydate);
PdfPCell header = new PdfPCell(new Phrase("Certificate of Analysis", titleFont));
header.Border = Rectangle.NO_BORDER;
header.HorizontalAlignment = Element.ALIGN_CENTER;
myTable.AddCell(header);
PdfPCell address = new PdfPCell(new Phrase("Company Address", AddressFont));
address.Border = Rectangle.NO_BORDER;
address.HorizontalAlignment = Element.ALIGN_RIGHT;
myTable.AddCell(address);
doc.Add(myTable);
Now the available width of your page will be divided in three, the date will be aligned to the left, the header will be centered, and the address will be aligned to the right. Obviously, you can add more data to a PdfPCell and more rows to the PdfPTable. This is just a simple proof of concept.
Another option, is to add the text at an absolute position (using coordinates). This can be done by using the ColumnText object. There are plenty of examples on this in The Best iText Questions on StackOverflow

How do I change the weight of a simulated bold font using itext

I am using the iText library to generate text. I am loading the Arial Unicode MS font which does not contain a bold style so iText is simulating the bold. This works fine, but the weight of the bold font appears too heavy compared with text generated using the Java API or even using Microsoft Word.
I tried to get the weight from the FontDescriptor, but the value returned is always 0.0
float weight = font.getBaseFont().getFontDescriptor(BaseFont.FONT_WEIGHT, fontSize);
Is there a way I can change the weight of a simulated bold font?
As an addendum to #Chris' answer: You do not need to construct those Object[]s as there is a Chunk convenience method:
BaseFont arialUnicodeMs = BaseFont.createFont("c:\\Windows\\Fonts\\ARIALUNI.TTF", BaseFont.WINANSI, BaseFont.EMBEDDED);
Font arial12 = new Font(arialUnicodeMs, 12);
Paragraph p = new Paragraph();
for (int i = 1; i < 100; i++)
{
Chunk chunk = new Chunk(String.valueOf(i) + " ", arial12);
chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, i/100f, null);
p.add(chunk);
}
document.add(p);
results in
EDIT
Sorry, I just realized after posting this that you're using iText but my answer is for iTextSharp. You should, however, be able to use most of the code below. I've updated the source code link to reference the appropriate Java source.
Bold simulation (faux bold) is done by drawing the text with a stroke. When iText is asked to draw bold text with a non-bold font it defaults to applying a stroke with a width of of the font's size divided by 30. You can see this in the current source code here. The magic part is setting the chunk's text rendering mode to a stroke of your choice:
//.Net code
myChunk.Attributes[Chunk.TEXTRENDERMODE] = new Object[] { PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, MAGIC_NUMBER_HERE, null };
//Java code
myChunk.attributes.put(Chunk.TEXTRENDERMODE, new Object[]{Integer.valueOf(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE), MAGIC_NUMBER_HERE, null});
Knowing that you can just apply the same logic but using your weight preference. The sample below creates four chunks, the first normal, the second faux-bold, the third ultra-heavy faux-bold and the fourth ultra-lite faux-bold.
//.Net code below but should be fairly easy to convert to Java
//Path to our PDF
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Path to our font
var ff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
//Normal document setup, nothing special here
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Register our font
FontFactory.Register(ff, "Arial Unicode MS");
//Declare a size to use throughout the demo
var size = 20;
//Get a normal and a faux-bold version of the font
var f = FontFactory.GetFont("Arial Unicode MS", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, size, iTextSharp.text.Font.NORMAL);
var fb = FontFactory.GetFont("Arial Unicode MS", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, size, iTextSharp.text.Font.BOLD);
//Create a normal chunk
var cNormal = new Chunk("Hello ", f);
//Create a faux-bold chunk
var cFauxBold = new Chunk("Hello ", fb);
//Create an ultra heavy faux-bold
var cHeavy = new Chunk("Hello ", f);
cHeavy.Attributes = new Dictionary<string, object>();
cHeavy.Attributes[Chunk.TEXTRENDERMODE] = new Object[] { PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, size / 10f, null };
//Create a lite faux-bold
var cLite = new Chunk("Hello ", f);
cLite.Attributes = new Dictionary<string, object>();
cLite.Attributes[Chunk.TEXTRENDERMODE] = new Object[] { PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, size / 50f, null };
//Add to document
var p = new Paragraph();
p.Add(cNormal);
p.Add(cFauxBold);
p.Add(cHeavy);
p.Add(cLite);
doc.Add(p);
doc.Close();
}
}
}

Change PDF's hyperlink display text

Using iTextSharp how can I modify the display text of hyperlink in a pdf document. I can change the annotation link, but my target is to change the displaying text of the hyperlink not the actual web link. Is it possible?
I don't want to add a new anchor, I just want to modify the existing anchor with a different text, not changing existing web link.
Thanks
use this,
using (FileStream msReport = new FileStream(Server.MapPath("~") + "/App_Data/" + DateTime.Now.Ticks + ".pdf", FileMode.Create))
{
Document doc = new Document(PageSize.LETTER, 10, 10, 20, 10);
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, msReport);
doc.Open();
Font link = FontFactory.GetFont("Arial", 12, Font.UNDERLINE, BaseColor.BLUE);
Anchor anchor = new Anchor("google", link);
anchor.Reference = "https://www.google.co.in";
doc.Add(anchor);
doc.Close();
}

How can I remove the default top margin on a pdf document with itextsharp?

I´m trying to get my pdf document to start at (0,0) however it seems that the document object has a default top margin which I cannot set to 0.
Is there a way to do this?
My code looks like the following
using (MemoryStream memoria = new MemoryStream())
{
Document pdf = new Document(new Rectangle(288, 144));
try
{
PdfWriter writer = PdfWriter.GetInstance(pdf, memoria);
pdf.Open();
pdf.SetMargins(0, 0, 0, 0);
PdfPTable tPrincipal = new PdfPTable(2);
tPrincipal .WidthPercentage = 100;
tPrincipal .DefaultCell.Border = 0;
tPrincipal .TotalWidth = 288f;
tPrincipal .LockedWidth = true;
....
I just can´t get to set the top margin to 0. It just doesnt care about my setting to (0,0,0,0) and leaves a top margin (around 50f).
You'll need to set your margins in your Document constructor, like this:
Document pdf = new Document(new Rectangle(288f, 144f), 0, 0, 0, 0);
You won't need to use the Document.SetMargins() method. I believe you'd use SetMargins()after you create a new page by calling Document.NewPage().
Option 1:
Document doc = new Document();
doc.setMargins(0 , 0 , 0 , 0);
Option 2:
Document pdf = new Document(new Rectangle(595 , 842 ), 0, 0, 0, 0);
Where, 595x842 is A4 size paper.
I did like below where “…/XYZ.pdf” is the path to generated pdf file download path.
PdfDocument pdfDoc = new PdfDocument(new com.itextpdf.kernel.pdf.PdfWriter(“…/XYZ.pdf”));
Document doc = new Document(pdfDoc);
doc.setMargins(0f , 0f , 0f , 0f);