Why these borders are showing when generating pdf using iTextsharp? - asp.net-mvc

I am trying to generate multiple pdfs into a single pdf, which I have achieved by using itextSharp , but while generating them few thing I came across,which are pointed below:
I am getting visible cell border just under image that i inserted .
Bottom image taking a space which flicks the image into another page, with extra visible border.
Also the paragraph didn't align to center.
Apart from these I also need that the text(in paragraph)comes from view(this code is doing in MVC).
How to solve these errors? Below is my code:
public byte[] GetPDF(string pHTML)
{
byte[] bPDF = null;
MemoryStream ms = new MemoryStream();
TextReader txtReader = new StringReader(pHTML);
//Rectangle pagesize = new Rectangle(864.0f, 1152.0f);
Document doc = new Document(PageSize.NOTE);
string path = Server.MapPath("PDFs");
PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);
HTMLWorker htmlWorker = new HTMLWorker(doc);
doc.Open();
for (int i = 1; i <= 5; i++)
{
doc.NewPage();
PdfPTable table= new PdfPTable(1);
table.TotalWidth = 500f;
table.LockedWidth = true;
table.HorizontalAlignment = 0;
table.DefaultCell.Border = Rectangle.NO_BORDER;
Image imageTopURL = Image.GetInstance("Top.PNG");
PdfPCell imgTopCell = new PdfPCell(imageTopURL);
Paragraph p = new Paragraph("XYZ", new Font(Font.FontFamily.COURIER, 32f, Font.UNDERLINE));
p.Alignment = Element.ALIGN_CENTER;
table.AddCell(imgTopCell);
table.AddCell(p);
Image imageMidURL = Image.GetInstance("Mid.PNG");
PdfPCell imgMidCell = new PdfPCell(imageMidURL);
Paragraph p1 = new Paragraph("ABC", new Font(Font.FontFamily.HELVETICA, 29f, Font.ITALIC));
p1.Alignment = Element.ALIGN_CENTER;
table.AddCell(imgMidCell);
imgMidCell.Border = 0;
table.AddCell(p1);
Image imageBotURL = Image.GetInstance("Bottom.PNG");
PdfPCell imgBotCell = new PdfPCell(imageBotURL);
table.AddCell(imgBotCell);
imageTopURL.ScaleAbsolute(505f, 270f);
imageMidURL.ScaleAbsolute(590f, 100f);
imageBotURL.ScaleAbsolute(505f, 170f);
doc.Open();
doc.Add(table);
htmlWorker.StartDocument();
htmlWorker.Parse(txtReader);
htmlWorker.EndDocument();
}
htmlWorker.Close();
doc.Close();
doc.Close();
bPDF = ms.ToArray();
return bPDF;
}

You are telling the table that default cells shouldn't have a border:
table.DefaultCell.Border = Rectangle.NO_BORDER;
This means that PdfPCell instances that are created implicitly won't get a border. For instance: if you do:
table.AddCell("Implicit cell creation");
Then that cell won't get a border.
However: you are creating a cell explicitly:
PdfPCell imgTopCell = new PdfPCell(imageTopURL);
In this case, the DefaultCell is never used. It is very normal that imgTopCell has a border. If you don't want a border for imgTopCell, you need to define the Border of imgTopCell like this:
imgTopCell.Border = Rectangle.NO_BORDER;
Regarding the alignment: it seems that you didn't read about the difference between text mode and composite mode. Please read the documentation, for instance:
Why does ColumnText ignore the horizontal alignment?
How to right-align text in a PdfPCell?
and many other FAQ entries about text mode and composite mode.
You are making a number of newbie mistakes that can all be fixed by reading the documentation. You have too many questions in one post. Please create new questions if my answer didn't solve every single of your problems. I see at least two more questions in your post (your question should actually be closed with as reason "Too broad").
Update:
In your comment, you added the following code snippet:
table.AddCell(new Paragraph(data.EmpName, new Font(Font.FontFamily.COURIER, 32f, Font.BOLD)));
You want to center this text.
First, let me explain that you are using the AddCell() method with a Paragraph as parameter. This doesn't really make sense as the Paragraph will be treated as a Phrase. You can as well write:
table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER ;
table.AddCell(new Phrase(data.EmpName, new Font(Font.FontFamily.COURIER, 32f, Font.BOLD)));
When you are passing a Phrase to the AddCell() method, you are
using text mode (the properties of the cell prevail over the properties of its elements), and
you are asking iTextSharp to create a PdfPCell.
In this case, iTextSharp will look at the DefaultCell and use the properties of that cell to create a new cell. If you want to center the content of that new cell, you need to define this at the level of the DefaultCell. All of this is explained in my answer to the following questions:
Why doesn't getDefaultCell().setBorder(PdfPCell.NO_BORDER) have any effect?
What is the PdfPTable.DefaultCell property used for?

Related

Add image to SVG element in dart [duplicate]

This question already has an answer here:
Dart svg ImageElement is not showing up
(1 answer)
Closed 9 years ago.
I am trying to show an (interchangeable) image as background to an ellipse or other various things I will manipulate later.
The problem is that I can't find how to load the image properly.
My code:
DivElement div = querySelector("#mainDiv");
svg.SvgElement svgElement = new svg.SvgSvgElement();
div.append(svgElement);
//div.setAttribute("background-color", "yellow");
svg.RectElement rec = new svg.RectElement();
rec.setAttribute("x", "0");
rec.setAttribute("y", "0");
rec.setAttribute("width",div.clientWidth.toString());
rec.setAttribute("height", div.clientHeight.toString());
//svgElement.children.add(rec);
Ellipse ell = new Ellipse() //my class. shows and allow to move it
..cx = 100
..cy= 100
..rx= 50
..ry= 50;
svgElement.children.add(ell.ellipse);
ImageElement image = new ImageElement(src: "2.jpg");
image.onLoad.listen((e) {
svgElement.children.add(image);
});
As you can see there is a Rectangle, which was my first attempt to show the image with various attributes (background-image, background..), then I thought to add the ImageElement directly after onLoad. Both Failed.
My next step should be to try with patterns, but I'm not sure if I can translate in Dart what I've read for javascript.
Edit: It would be nice to be able to load the image as well, so that I can read attributes like dimensions.
Edit2: Since I can't add an answer, here is the code I made by checking the "duplicate" original one.
import 'dart:svg' as svg;
//...
DivElement div = querySelector("#mainDiv");
svg.SvgElement svgElement = new svg.SvgSvgElement();
div.append(svgElement);
Ellipse ell = new Ellipse()
..cx = 100
..cy= 100
..rx= 50
..ry= 50;
svg.ImageElement image = new svg.ImageElement();
svgElement.children.add(image);
image.setAttribute('x', '0');
image.setAttribute('y', '0');
image.setAttribute('width', '100%');
image.setAttribute('height', '100%');
image.getNamespacedAttributes('http://www.w3.org/1999/xlink')['href'] = '2.jpg';
svgElement.children.add(ell.ellipse);
I haven't tried it but I assume that the onLoad event will not fire before the element isn't added to the DOM.
You should add the image just after creating the element.
You could alternatively set display: none and change to display: auto when onLoad fires.

thin border when printing pdf

We use Version 8.1 from ABCPDF to generate some nice PDF documents from html.
Now we discovered that printing from within Adobe Reader, will add some thin borders at the top and bottom of the page, that are not visible when the document is displayed. Also when printing to XPS, those lines are not visible.
I guess we must have missed some setting that avoids that?
At the moment we print pages like that:
using (var doc = new WebSupergoo.ABCpdf8.Doc())
{
doc.HtmlOptions.DoMarkup = false;
doc.HtmlOptions.AddLinks = false;
doc.HtmlOptions.FontEmbed = true;
doc.HtmlOptions.Engine = EngineType.Gecko;
//in case that we need to create more than 1 page, we need go get the PageId and use it
int pdfPageId = doc.AddImageHtml(html);
while (true)
{
doc.FrameRect();
if (!doc.Chainable(pdfPageId))
break;
doc.Page = doc.AddPage();
pdfPageId = doc.AddImageToChain(pdfPageId);
}
for (int i = 1; i <= doc.PageCount; i++)
{
doc.PageNumber = i;
doc.Flatten();
}
doc.Save(pathToSave);
}
I know the websupergoo guys are very friendly and reply fast.
But I think this could help other people as well, so I write it here instead of sending them an email.
Update:
I tried to get rid of the linex by changing the size of the printed document. I actually try to print for A4 Papersize. I added a line of code to change the setting for the MediaBox (the documentation suggested that this should be possible "doc.MediaBox = "A4"", but it's not directly assignable):
//set the printed area to A4
doc.MediaBox.String = "A4";
Result: The lines got thicker and can now even be seen before printing in both AdobeReader and Foxit Reader. this is not yet the solution.
Update2:
I need to set the Rect of the document as well:
//set the printed area to A4
doc.Rect.String ="A4";
doc.MediaBox.String = "A4";
Result: the lines are now drawn on the sides and can only be seen when printing. That's still not the complete solution.
Well well, copy pasting code from the web has it's dangers!
This line adds the Frame around the content:
doc.FrameRect();
all I had to do was remove it.. and no more lines are displayed.
I completely overlooked that until now.
Before I also tried the following, which didn't work as expected:
//set the width to 0, so Rectancles have no width
doc.Width = 0;
// set the color to white, so borders of Rectangles should not be black
doc.Color.String = "255 255 255"; //Edited based on the comments.

Putting several images next to each other in a pdfcell with itextsharp

I'm using itextsharp with a aspmvc project to create PDF versions of some of my pages. I have a very basic parser which takes simple html (plus some style info supplied seperately) and creates a pdf. When my parser encounts a table it loops over rows then cells, creating a PdfPCell for each cell. It then loops over child elements of the cell adding them to the PdfPCell. It's pretty basic but it's worked for me so far.
The problem is that I now have a table one column of which contains a number of icons, indicating different status for the row. When these images get added then end up one above the other in the pdf, instead of next to each other.
I create the image with
Dim I As iTextSharp.text.Image = Image.GetInstance(HttpContext.Current.Server.MapPath(El.Attributes("src").InnerText))
I have tried
I.Alignment = Image.TEXTWRAP Or Image.ALIGN_LEFT Or Image.ALIGN_MIDDLE
and adding a text chunk afterwards containing a space but it doesn't help. The only suggestion I have seen is to use I.SetAbsolutePosition(). I'd rather avoid absolute position but am prepared to try it - except I can't work out how to find the current X position to use?
Any help much appreciated.
Adam
To get the proper side-by-side flow, wrap the images/text in a Paragraph object, adding them one by one using Chunk and Phrase objects. Something (sorry, I don't do VB) like this:
PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
p.Add(new Phrase("Test "));
p.Add(new Chunk(image, 0, 0));
p.Add(new Phrase(" more text "));
p.Add(new Chunk(image, 0, 0));
p.Add(new Chunk(image, 0, 0));
p.Add(new Phrase(" end."));
cell.AddElement(p);
table.AddCell(cell);
table.AddCell(new PdfPCell(new Phrase("test 2")));
document.Add(table);
EDIT: One way to add whitespace between the images. Will only work with images; if you try this with mixed text/image(s), they will overlap:
PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
float offset = 20;
for (int i = 0; i < 4; ++i) {
p.Add(new Chunk(image, offset * i, 0));
}
cell.AddElement(p);
table.AddCell(cell);
table.AddCell(new PdfPCell(new Phrase("cell 2")));
document.Add(table);
See the Chunk documentation.

How to create PieSeries interpolation in flex 4.5 at run time

i make a PieChart at run time, and i want to interpolate data change, but i have some difficult.
The Code is here:
//Pie Chart
pieChart.dataProvider = expenses;
var pieSeries:PieSeries = new PieSeries();
pieSeries.nameField = "position";
pieSeries.field = "value";
pieSeries.explodeRadius = 0.08;
pieChart.series = null;
pieChart.series.push(pieSeries);
I found two method, but i don't know how to use that >.<:
pieSeries.beginInterpolation
pieSeries.interpolate
1) First create a SeriesInterpolate class instance and customize it however you want.
2) You can set the showDataEffect style of your pieSeries object to the interpolate object that you just created.
Whalah.. whenever your data changes the interpolator will get triggered.
See the code snippet below..
I've also created an example application with source enabled.
goto: http://befreestudiosllc.com/demos/flex4/charting/seriesInterpolate/ and right-click to view source.
// Create an interpolator and customize its properties
var interpolateDataIn:SeriesInterpolate = new SeriesInterpolate();
interpolateDataIn.duration = 1000;
var pieSeries:PieSeries = new PieSeries();
pieSeries.setStyle("showDataEffect", interpolateDataIn); // apply interpolators to your series through show/hide dataEffects

how I can place an image just in one cell using npoi

I'm using npoi to generate excel docs. I have a requirement to add images to cells. Using the following code i can insert images into my doc. However the image span many cells. How can i ensure that the image just fits inside once cell.
public ActionResult NPOICreate()
{
try
{
FileStream fs = new FileStream(Server.MapPath(#"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.ReadWrite);
HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
var sheet = templateWorkbook.GetSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
HSSFClientAnchor anchor;
anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short)6, 5);
anchor.AnchorType = 2;
var picture = patriarch.CreatePicture(anchor, LoadImage(#"D:\dev\Website/HumpbackWhale.jpg", templateWorkbook));
picture.Resize();
picture.LineStyle = HSSFPicture.LINESTYLE_DASHDOTGEL;
sheet.ForceFormulaRecalculation = true;
MemoryStream ms = new MemoryStream();
templateWorkbook.Write(ms);
TempData["Message"] = "Excel report created successfully!";
return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
}
catch (Exception ex)
{
TempData["Message"] = "Oops! Something went wrong.";
return RedirectToAction("NPOI");
}
}
To the best of my knowledge, it isn't possible to assign an image object to a particular cell within Excel.
This is not a limitation of POI/NPOI, but rather the way Excel works: Pictures inserted into a spreadsheet just float (over the spreadsheet grid per se)...
At best one can make believe it is in the cell by ensuring that the size and position of the cell and of the picture match perfectly. There is a property of the picture (See "Format Picture" dialog, Properties section, also accessible through POI I'm sure) which allows to specify whether the picture will move and/or resize itself following actions on rows/cells surrounding it, but in the end, pictures remain a floating object very loosely related to a cell at best.
A common trick to assign a picture to a cell is by way of comments. The picture is then more formally bound to the cell but it is not shown as content but rather a comment data.
See for example this recipe. The idea is to use the background of the comment to be a color with a special fill effect which is the picture we wish to associate with the cell. Here again, there's got to be a way of achieving this programmatically with NPOI, but I cannot affirm this firsthand.
here's something you can try:
You see that property, anchor.AnchorType = 2;? try setting that to 0 or 3 and see what it does. In the C# (NPOI) port, 0 will fit the image in just one cell with option 0.
Here's some example code (used in a C# Asp.net project, just in case someone wanders here that needs it):
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet1 = hssfworkbook.CreateSheet(sheetName);
//map the path to the img folder
string imagesPath = System.IO.Path.Combine(Server.MapPath("~"), "img");
//grab the image file
imagesPath = System.IO.Path.Combine(imagesPath, "image.png");
//create an image from the path
System.Drawing.Image image = System.Drawing.Image.FromFile(imagesPath);
MemoryStream ms = new MemoryStream();
//pull the memory stream from the image (I need this for the byte array later)
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//the drawing patriarch will hold the anchor and the master information
HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();
//store the coordinates of which cell and where in the cell the image goes
HSSFClientAnchor anchor = new HSSFClientAnchor(20, 0, 40, 20, 3, 10, 4, 11);
//types are 0, 2, and 3. 0 resizes within the cell, 2 doesn't
anchor.AnchorType = 2;
//add the byte array and encode it for the excel file
int index = hssfworkbook.AddPicture(ms.ToArray(), HSSFPicture.PICTURE_TYPE_PNG);
HSSFPicture signaturePicture = patriarch.CreatePicture(anchor, index);
It's possible by three steps.
First, you should insert the picture
Second, add the ClientAnchor to the file to locate the picture to some cells
Third, resize the picture using tricky way otherwise it's hard to make a picture inside a cell

Resources