Using Bootstrap Glyph icons in iTextSharp - asp.net-mvc

I am building a .NET/C#/MVC system that uses Bootstrap and iTextSharp.
I have two Glyph font icons that I would also like to use when generating a PDF document using iTextSharp.
The only way I know to include and image in a PDF, is to designate a stream to an image:
Stream imageStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Onlineeksamen.Web.Resources.ios7-phone1-icon.png");
Image image = Image.GetInstance(imageStream);
The Glyph icons are available in following files:
fonts\glyphicons-halflings-regular.eot
fonts\glyphicons-halflings-regular.svg
fonts\glyphicons-halflings-regular.ttf
fonts\glyphicons-halflings-regular.woff
I now have following sample based on the comment from jme but it doesnt work - I assume that the icons are characters in the font:
outputStream = new MemoryStream();
document = new Document(PageSize.A4, margin, margin, margin, margin);
pdfWriter = PdfWriter.GetInstance(document, outputStream);
document.Open();
pdfContentByte = pdfWriter.DirectContent;
PageHeight = document.PageSize.Height;
pdfContentByte.SetColorStroke(BaseColor.BLACK);
string fontFile = String.Format("{0}fonts\\glyphicons-halflings-regular.ttf", HostingEnvironment.ApplicationPhysicalPath);
BaseFont customfont = BaseFont.CreateFont(fontFile, BaseFont.CP1252, BaseFont.EMBEDDED);
pdfContentByte.SetFontAndSize(customfont, 12);
pdfContentByte.BeginText();
pdfContentByte.SetTextMatrix(100, PageHeight.Value - 100);
pdfContentByte.ShowText("This should be glyphs");
pdfContentByte.EndText();
document.Close();
return outputStream.ToArray();
Thank you in advance
Soeren D.

Related

How to make image source change after handle without display another one on canvas output (OpenCV.js)

I am using OpenCV.js in Ionic 3 to make a scanner app.
I have a .ts file with rotate function like this:
rotateRight() {
let src = cv.imread('img');
let dst = new cv.Mat();
let dsize = new cv.Size(src.rows, src.cols);
let center = new cv.Point(src.cols / 2, src.rows / 2);
let M = cv.getRotationMatrix2D(center, -90, 1);
cv.warpAffine(src, dst, M, dsize, cv.INTER_LINEAR, cv.BORDER_CONSTANT, new cv.Scalar());
cv.imshow('canvasOutput', dst);
src.delete(); dst.delete(); M.delete();
}
And I have code like this in .html file with img source to get and canvas to display new image after processing:
<img id="img" [src]="picture" *ngIf="picture" />
<canvas id="canvasOutput" ></canvas>
My problem is I just want to display only one image in my .html file, I want after processing the new image will display in the img source from the begin instead of having another display like canvas.
Is there any way to do that?
Thanks for helping!
After asking I found the answer by myself.
Firstly, get element canvasOutput and img from HTML, then change image's source to canvasOutput with base64 format:
var canvasOutput = document.getElementById('canvasOutput') as HTMLCanvasElement;
let picture = document.getElementById("img") as HTMLImageElement;
picture.src = canvasOutput.toDataURL();
Lastly set 's style to visibility: hidden to hide canvas tag.

How to generate searchable PDF using swift

Right now I am able to generate a PDF using the code below. The issue is that the generated PDF is not searchable nor its texts copyable. (like the whole PDF is a image).
Is there a way to create a PDF using ios (Swift) that has its texts copyable/searchable?
Part of my code that generates the pdf:
let pdfFrame:CGRect = CGRect(x: 0, y: 0, width: sourceView.contentSize.width, height: sourceView.contentSize.height);
UIGraphicsBeginPDFContextToFile(dataFilename, pdfFrame, nil);
UIGraphicsBeginPDFPageWithInfo(pdfFrame, nil);
sourceView.contentOffset = CGPoint.zero;
sourceView.frame = pdfFrame;
let pdfContext : CGContext = UIGraphicsGetCurrentContext()!;
sourceView.layer.render(in: pdfContext);
UIGraphicsEndPDFContext();
In order to generate a PDF that is searchable, you need to create a PDF file that contains text. Your PDF is being created only with images. You can't use render(in:). Whatever text you want in the PDF needs to be drawn into the PDF context. See How to draw text in PDF context in Swift? for an example.

Why these borders are showing when generating pdf using iTextsharp?

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?

Dynamically generated image is bigger than original image in asp.net mvc

In my asp.net mvc application I am uploading image and resizing same to 800x600 pixel size, converting it to PNG format and then saving it to disk. I am using following code
public void ResizeImg(HttpPostedFileBase UploadImg)
{
if (UploadImg != null)
{
Stream s = UploadImg.InputStream;
Image UploadedImg = Image.FromStream(s);
int Width = UploadedImg.Width;
int Height = UploadedImg.Height;
int ResizeWidth = 800, ResizeHeight = 600;
using (var newImage = new Bitmap(ResizeWidth, ResizeHeight))
using (var graphics = Graphics.FromImage(newImage))
using (var stream = new MemoryStream())
{
/* Resizing */
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.Default;
graphics.PixelOffsetMode = PixelOffsetMode.Default;
graphics.DrawImage(UploadedImg, new Rectangle(0, 0, ResizeWidth, ResizeHeight));
newImage.Save(stream, ImageFormat.Png);
/* Saving resized image */
FileStream fileStream = File.Create(HttpContext.Current.Server.MapPath("~/Images/GeneratedBarcode/testing.png"), (int)stream.Length);
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
}
code is working properly. But issue is that original image is 1024x768 jpg image which is 858 KB and after resize it is 800x600 png image with 1.16MB
Why after resizing to smaller size and converting to png image size become larger than origianl.
I found solution for that issue. Instead of saving image in PNG formate, I am saving it in JPEG formate like this:
//newImage.Save(stream, ImageFormat.Png);
newImage.Save(stream, ImageFormat.Jpeg);
I don't know why but it works for me.

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