Change line Separator color using iText7 - itext7

I want to change the line Separator using iText7 but did not know how to use line.setColor(Color.RED); from the example here.
SolidLine line = new SolidLine(1f);
line.setColor(Color.RED);
LineSeparator ls = new LineSeparator(line);

You can try the following code using which one should be able to set any color on SolidLine.
PdfDocument pdf = new PdfDocument(new
PdfWriter("src/main/resources/test/output.pdf"));
Document document = new Document(pdf);
SolidLine line = new SolidLine(1f);
line.setColor(ColorConstants.BLUE);
LineSeparator ls = new LineSeparator(line);
ls.setWidth(UnitValue.createPercentValue(50));
ls.setMarginTop(5);
document.add(ls);
document.add(new Paragraph(" test document pdf..."));
document.close();

Related

iText 5 ColumnText to iText7 ColumnDocumentRenderer alignment issue

We are in the process of migrating from iText 5 to iText7. ColumnText is used in few places in our existing code. According to the following https://www.slideshare.net/iTextPDF/oops-i-broke-my-api?from_action=save
we tried to run a sample to test iText7 solution based on ColumnDocumentRenderer. Even though it is working fine, we are seeing a minor difference in the alignment. Apparently, iText5 code is aligning the text to the bottom, but iText7 is not doing that.
iText 5 code
Document document = new Document();
PdfWriter writer =
PdfWriter.getInstance(document, new FileOutputStream("D:\\Temp Files\\Test.pdf"));
document.open();
ColumnText ct = new ColumnText(writer.getDirectContent());
Font normal = new Font(FontFamily.TIMES_ROMAN, 12);
Paragraph p = new Paragraph("Text", normal);
ct.addElement(p);
int status = ColumnText.START_COLUMN;
Rectangle[] columns = {new Rectangle(36, 36, 290, 806)};
while(ColumnText.hasMoreText(status)) {
ct.setSimpleColumn(columns[0]);
status = ct.go();
}
document.close();
iText 7 code
PdfDocument pdf = new PdfDocument(new PdfWriter("D:\\Temp Files\\Test i7 ColumnText.pdf"));
Document document = new Document(pdf);
Rectangle[] columns = {new Rectangle(36, 36, 254, 770)};
document.setRenderer(new ColumnDocumentRenderer(document, columns));
BufferedReader br = new BufferedReader(new StringReader("Text"));
String line;
PdfFont normal = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
while ((line = br.readLine()) != null) {
document.add(new Paragraph(line).setFont(normal));
}
document.close();
There is no alignment or padding set in either case. Not sure if there is anything else that we need to set in iText7. We want to retain the placement of the text, which is very crucial while trying to generate dynamic PDF's. How to maintain the placement of the text between iText 5 and iText 7?
Note: Enclosed screenshot for reference.
iText5 Vs iText7
Left hand side pdf is created by 5 and right hand side is created by 7. The rectangular box was drawn to show how itext 5 is rendering Text aligned to the bottom, but itext 7 is placing the Text little bit above the base line. How to fix itext7 code to place Text similar itext 5?

iText header: add logo img on the left side and text on the right side

I´m new to iText.
I would like to make a header that will be the same on each page.
The page header will look something like this:
logo.jpg some text
How can I do that?
I have read this link:
http://developers.itextpdf.com/question/how-generate-report-dynamic-header-pdf-using-itextsharp
and I have a problem because I cant add an image to pharse.
Image image = Image.GetInstance(Server.MapPath(mclLogo));
phrase.Add(image);
Throws the Error:
Insertion of illegal Element: 32
Edit: I have tried with paragraph and glue:
Paragraph paragraph = new Paragraph();
paragraph.Add(image);
paragraph.Add(new Chunk(glue));
paragraph.Add("text on the right");
and the output is 2 lines.
somthing link this:
logo.jpg
some text
edit 2:
I have read this:
http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/chapter-1-introducing-basic-building-blocks
espacially the part:
Image fox = new Image(ImageDataFactory.create(FOX));
Image dog = new Image(ImageDataFactory.create(DOG));
Paragraph p = new Paragraph("The quick brown ")
.add(fox)
.add(" jumps over the lazy ")
.add(dog);
document.add(p);
but I use iText5 and I dont find any way how to make a picture and text in the same line.
Try below code, which works with two different Header plot which plotted at right end with image and Left end one with text.
public override void OnStartPage(PdfWriter writer, iTextSharp.text.Document document)
{
PdfPTable HeaderPlot = new PdfPTable(new float[] { 10F });//Header plot 1
PdfPTable HeaderPlot2 = new PdfPTable(new float[] { 10F });//Header plot 2
PdfPCell cell;//cell 1
PdfPCell cell2;// cell 2
HeaderPlot.TotalWidth = 570F; //width for Header plot 1
HeaderPlot2.TotalWidth = 570F;//width for Header plot 2
cell = new PdfPCell();
cell2 = new PdfPCell();
string path = headerpath;
FileInfo f2 = new FileInfo(path);
FileStream fs = new FileStream(f2.FullName,
FileMode.Open, FileAccess.Read);
BinaryReader rdr = new BinaryReader(fs);
byte[] fileData = rdr.ReadBytes((int)fs.Length);
Image image = Image.GetInstance(fileData);
image.ScaleAbsolute(80, 40); //adjusting image size
image.Alignment = Element.ALIGN_CENTER;
cell = new PdfPCell(image)
{
Border = 0,
HorizontalAlignment = Element.ALIGN_TOP,
VerticalAlignment = Element.ALIGN_TOP
};//Header image position
Font font = FontFactory.GetFont("Calibri Light", 8f, Font.NORMAL,
iTextSharp.text.BaseColor.BLACK);//Initializing font
cell2 = new PdfPCell(new Phrase("Text", font))
{
Border = 0,
HorizontalAlignment = Element.ALIGN_LEFT,
VerticalAlignment = Element.ALIGN_TOP
};//Header Text position
HeaderPlot.AddCell(cell);//adding cell 1 to Headerplot 1
HeaderPlot.WriteSelectedRows(0, -1, 480, 835,
writer.DirectContent);//Position of the header on right end, coordinates on right end(480,835)
HeaderPlot2.AddCell(cell2);//adding cell 2 to Headerplot 2
HeaderPlot2.WriteSelectedRows(0, -1, 40, 835,
writer.DirectContent);//Position of the header on left end, coordinates on left end(40,835)
}

NPOI XWPF how can I place text on a single line that is both left & right justified?

I'm new to using NPOI XWPF and trying to create my first document, so far it's going well. The only issue I have left is trying to place text on the same line that is both left and right justified, I want it to look like:
Area: 1(Left Jstfd) Grade Level/Course: 10th Grade Reading (Right Jstfd)
Below is the code snippet I'm using, it's just pushing all the text together on the left side of the page...blah
XWPFParagraph p2 = doc.CreateParagraph();
p2.Alignment = ParagraphAlignment.LEFT;
XWPFRun r3 = p2.CreateRun();
r3.SetBold(true);
r3.FontFamily = "Times New Roman";
r3.FontSize = 12;
r3.SetText("Area: " + ah.schoolArea);
XWPFRun r4 = p2.CreateRun();
r4.SetBold(true);
r4.FontFamily = "Times New Roman";
r4.FontSize = 12;
r4.SetText("Grade Level/Course: " + ah.filterParm);
Before trying to accomplish a task in (N)POI, it's always good to realize how said task is accomplished in Microsoft Word itself. You can't simply split a paragraph half-way a line, what you do is
Add a tab stop at the end of the line
Set it to right-aligned.
Type text on the left, hit tab, type text on the right
Unfortunately, it doesn't seem XWPFParagraph exposes tabstop functionality at this point. However, XWPFParagraph is a wrapper around the CT_P class, which maps 1:1 onto the underlying Office XML format. Using reflection, we can access this private field and use it to directly add the tabstop.
Sample code:
var paragraph = document.CreateParagraph();
var memberInfo = typeof(XWPFParagraph).GetField("paragraph", BindingFlags.NonPublic | BindingFlags.Instance);
if (memberInfo == null)
{
throw new Exception("Could not retrieve CT_P from XWPFParagraph");
}
var internalParagraph = (CT_P) memberInfo.GetValue(paragraph);
CT_PPr pPr = internalParagraph.AddNewPPr();
CT_Tabs tabs = pPr.AddNewTabs();
CT_TabStop tab = tabs.AddNewTab();
tab.pos = "9000";
tab.val = ST_TabJc.right;
var run = paragraph.CreateRun();
run.SetText("Left aligned");
run.AddTab();
run = paragraph.CreateRun();
run.SetText("Right aligned");
Result:

How can I get my PdfPTable's border and background color to display (iTextSharp)?

As you can see, I've got a table which sports borders and a background color (Section 1):
...but section 3 lacks these sartorial refinements, and I don't know why.
Here is the pertinent code for section 1 (which displays as it should):
PdfPTable tblHeadings = new PdfPTable(3);
tblHeadings.WidthPercentage = 100;
tblHeadings.SpacingBefore = 10f;
float[] headingRowWidths = new float[] { 550f, 50f, 400f };
tblHeadings.SetWidths(headingRowWidths);
tblHeadings.HorizontalAlignment = Element.ALIGN_LEFT;
Phrase phrasesec1Heading = new Phrase("Section 1: Payment Information", timesRoman9BoldFont);
PdfPCell cellSec1Heading GetCellForBorderedTable(phrasesec1Heading, Element.ALIGN_LEFT, ucscgold);
tblHeadings.AddCell(cellSec1Heading);
. . .
doc.Add(tblHeadings);
...and here for section 3 (which doesn't display as it should):
// Section 3
PdfPTable tblSection3 = new PdfPTable(1);
tblSection3.WidthPercentage = 100;
tblSection3.SpacingBefore = 10f;
//tblSection3.HorizontalAlignment = Element.ALIGN_LEFT;
Chunk sec3PayeeStatus = new Chunk("Section 3: Payee Status", timesRoman9BoldFont);
Chunk requiredFields = new Chunk(" * Required Fields", timesRoman9BoldRedFont);
Paragraph parSection3 = new Paragraph();
parSection3.Add(sec3PayeeStatus);
parSection3.Add(requiredFields);
//Phrase phrasesec1Heading = new Phrase("Section 1: Payment Information", timesRoman9BoldFont);
PdfPCell cellSec3Heading = GetCellForBorderedTable(parSection3, Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(parSection3);
What am I missing or forgetting? The difference in the table creation and setup is in the number of cells/columns, and related declaration (float array) and property (setWidths()). The code adding to the PdfPCell differs in that a Phrase
is used for Section 1 (which displays as I want it to), and a Paragraph is used for section 3 (which doesn't), but I tried that:
// try using a Phrase instead of a Paragraph
Chunk sec3PayeeStatus = new Chunk("Section 3 PayeeStatus",
timesRoman9BoldFont);
Chunk requiredFields = new Chunk(" * Require Fields",
timesRoman9BoldRedFont);
Phrase phraseSection3 = new Phrase();
phraseSection3.Add(sec3PayeeStatus);
phraseSection3.Add(requiredFields);
PdfPCell cellSec3Heading GetCellForBorderedTable(phraseSection3,
Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(phraseSection3);
...but that did no better, in fact was a little worse, because the "SpacingBefore" didn't seem to "take"
Finally (so far), I tried using Phrases instead of Chunks, like so:
Phrase sec3PayeeStatus = new Phrase("Section 3: Payee Status", timesRoman9BoldFont);
Phrase requiredFields = new Phrase(" * Required Fields", timesRoman9BoldRedFont);
Paragraph parSection3 = new Paragraph();
parSection3.Add(sec3PayeeStatus);
parSection3.Add(requiredFields);
PdfPCell cellSec3Heading = GetCellForBorderedTable(parSection3, Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(parSection3);
...but that is no better, worse, or different than the first attempt (at least I get the vertical space back, though, separating sections 2 and 3).
What do I have to do to display the cell borders and background color?
UPDATE
Here's GetCellForBorderedTable():
private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color)
{
PdfPCell cell = new PdfPCell(phrase);
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
cell.BackgroundColor = color;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
return cell;
}
The problem was (not "visible" to me until I compared the code in a code comparison utility, namely KDiff3) that I was adding the Paragraph, not the table, to the doc:
doc.Add(parSection3);
Now that I've changed that to:
doc.Add(tblSection3);
...it works.

Parse PDF with ABCPDF

I want to parse a PDF document I download with ABCPDF, but I cant find any elements in the document or how to reach them and iterate them. I want to parse out some text.
var webClient = new WebClient();
var bytes = webClient.DownloadData("http://test.com/test.pdf");
var doc = new Doc();
doc.Read(bytes);
Use the Doc.GetText method to extract content from the current page, specifying the format in which content is to be returned.
doc.PageNumber = 1;
string pageContent = doc.GetText("Text");
The example above will return plain text in layout order. Specifying "SVG" or "SVG+" returns additional information along with the text, such as style and position.

Resources