Hide an Image in itextsharp - c#

What I am trying to achieve is to hide the image (either by opacity or transparency) using itextsharp. So far the image is being show as below:
string webURL = "X:/XXXXXX/web.png";
iTextSharp.text.Image webIcon = iTextSharp.text.Image.GetInstance(webURL);
webIcon.Annotation = new Annotation(0,0,0,0, "http://www.xxxxx.com");
webIcon.ScaleAbsolute(35f, 35f);
webIcon.SetAbsolutePosition(227,23);
webIcon.Transparency = new int[] {0,0 };
//state.FillOpacity = 0.2f;
//webIcon.GrayFill = 0.2f;
doc.Add(webIcon);
How do I change the transparency so the image's visibility is null?

You need to use PdfGState. In your case:
var writer = PdfWriter.GetInstance(document, output);
document.Open();
string webURL = "http://www.apache.org/foundation/press/kit/feather.png";
Image webIcon = Image.GetInstance(webURL);
webIcon.Annotation = new Annotation(0, 0, 0, 0, "http://www.google.com");
webIcon.ScaleAbsolute(35f, 35f);
webIcon.SetAbsolutePosition(227, 23);
PdfContentByte canvas = writer.DirectContentUnder;
canvas.SaveState();
PdfGState state = new PdfGState();
state.FillOpacity = 0.6f; // THIS is where you set opacity
canvas.SetGState(state);
canvas.AddImage(webIcon);
canvas.RestoreState();
document.Close();
Hope it helps

Related

Watermark a pdf document with itext 7 instead of iTextSharp

This was my code for itextsharp which worked ok. It displayed "Quote Only" in the middle of each page in a pdf file.
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath(#"~\Content\WaterMarkQuoteOnly.png"));
PdfReader readerOriginalDoc = new PdfReader(File(all, "application/pdf").FileContents);
int n = readerOriginalDoc.NumberOfPages;
img.SetAbsolutePosition(0, 300);
PdfGState _state = new PdfGState()
{
FillOpacity = 0.1F,
StrokeOpacity = 0.1F
};
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(readerOriginalDoc, ms, '\0', true))
{
for (int i = 1; i <= n; i++)
{
PdfContentByte content = stamper.GetOverContent(i);
content.SaveState();
content.SetGState(_state);
content.AddImage(img);
content.RestoreState();
}
}
//return ms.ToArray();
all = ms.GetBuffer();
}
This is my new itext 7 code, this also displays the watermark but the position is wrong. I was dismayed to see that you cant add an image to the canvas but you have to add ImageData when the position is being set on the image. The image is also way smaller and back to front.
var imagePath = Server.MapPath(#"~\Content\WaterMarkQuoteOnly.png");
var tranState = new iText.Kernel.Pdf.Extgstate.PdfExtGState();
tranState.SetFillOpacity(0.1f);
tranState.SetStrokeOpacity(0.1f);
ImageData myImageData = ImageDataFactory.Create(imagePath, false);
Image img = new Image(myImageData);
img.SetFixedPosition(0, 300);
var reader = new PdfReader(new MemoryStream(all));
var doc = new PdfDocument(reader);
int pages = doc.GetNumberOfPages();
using (var ms = new MemoryStream())
{
var writer = new PdfWriter(ms);
var newdoc = new PdfDocument(writer);
for (int i = 1; i <= pages; i++)
{
//get existing page
PdfPage page = doc.GetPage(i);
//copy page to new document
newdoc.AddPage(page.CopyTo(newdoc)); ;
//get our new page
PdfPage newpage = newdoc.GetPage(i);
Rectangle pageSize = newpage.GetPageSize();
//get canvas based on new page
var canvas = new PdfCanvas(newpage);
//write image data to new page
canvas.SaveState().SetExtGState(tranState);
canvas.AddImage(myImageData, pageSize, true);
canvas.RestoreState();
}
newdoc.Close();
all = ms.GetBuffer();
ms.Flush();
}
You are doing something strange with the PdfDocument objects, and you are also using the wrong AddImage() method.
I am not a C# developer, so I rewrote your example in Java. I took this PDF file:
And I took this image:
Then I added the image to the PDF file using transparency with the following result:
The code to do this, was really simple:
public void createPdf(String src, String dest) throws IOException {
PdfExtGState tranState = new PdfExtGState();
tranState.setFillOpacity(0.1f);
ImageData img = ImageDataFactory.create(IMG);
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(reader, writer);
for (int i = 1; i <= pdf.getNumberOfPages(); i++) {
PdfPage page = pdf.getPage(i);
PdfCanvas canvas = new PdfCanvas(page);
canvas.saveState().setExtGState(tranState);
canvas.addImage(img, 36, 600, false);
canvas.restoreState();
}
pdf.close();
}
For some reason, you created two PdfDocument instances. This isn't necessary. You also used the AddImage() method passing a Rectangle which resizes the image. Also make sure that you don't add the image as an inline image, because that bloats the file size.
I don't know which programming language you are using. For instance: I am not used to variables that are created using var such as var tranState. It should be very easy for you to adapt my Java code though. It's just a matter of changing lowercases into uppercases.

Add image with text in header of every page in pdf file using itextsharp

When we use below code it add only one image. Is any other option to add image & text on every page?
private void AddHeader(string filephysicalpath, string nfile)
{
byte[] bytes = System.IO.File.ReadAllBytes(filephysicalpath);
String path = ConfigurationManager.AppSettings["Documentheader"].ToString() + Session["headerImg"];
Stream inputImageStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
Font blackFont = FontFactory.GetFont("Arial", 12, Font.BOLD, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
string footer = Convert.ToString(Session["Footer"]);
if (Session["Footer"] != null)
{
// Phrase ft = new Phrase(footer, blackFont);
float marginLR = 36;
float marginB = 2;
float footerHeight = 10;
Rectangle pagesize = reader.GetCropBox(i);
if (pagesize == null)
{
pagesize = reader.GetPageSize(i);
}
Rectangle rect = new Rectangle(
pagesize.Left + marginLR, pagesize.Top + marginB,
pagesize.Right - marginLR, pagesize.Top + marginB + footerHeight
);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(rect.Left, rect.Top - image.ScaledHeight);
var pdfContentByte = stamper.GetOverContent(1);
pdfContentByte.AddImage(image);
inputImageStream.Seek(0L, SeekOrigin.Begin);
// ct.AddElement(new PdfPTableHeader (image));
}
}
}
reader.Close();
bytes = stream.ToArray();
}
System.IO.File.WriteAllBytes(filephysicalpath, bytes);
}
In your loop you do
var pdfContentByte = stamper.GetOverContent(1);
pdfContentByte.AddImage(image);
I.e. you always use the OverContent of page 1 and add the image to it. Instead you should use the OverContent of page i:
var pdfContentByte = stamper.GetOverContent(i);
pdfContentByte.AddImage(image);
Furthermore, you should import the image only once, i.e. move the line
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
above the loop.
Have you try to set inputImageStream to beggining before next use?
inputImageStream.Seek(0L, SeekOrigin.Begin);
Meybe its pointer is on the end of stream and next call return empty image?

It is possible to cut an image of ItextSharp.Text.Image?

I'm creating a pdf file from an large image, but my image is too large, and it does not fit in the only page. then i need split this image to create more pages.
any idea?
public FileResult ResultadoParaPdf(string file)
{
string fileStringReplace = file.Replace("data:image/png;base64,", "");
var image = Convert.FromBase64String(fileStringReplace);
const int HorizontalMargin = 40;
const int VerticalMargin = 40;
using (var outputMemoryStream = new MemoryStream())
{
using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
{
iTextSharp.text.pdf.PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
pdfWriter.CloseStream = false;
pdfDocument.Open();
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
Image img = Image.GetInstance(image);
img.WidthPercentage = 100;
PdfPCell c = new PdfPCell(img, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFit(750f, 750f);
table.AddCell(c);
pdfDocument.Add(table);
pdfDocument.Close();
byte[] created = outputMemoryStream.ToArray();
outputMemoryStream.Write(created, 0, created.Length);
outputMemoryStream.Position = 0;
return File(created, "application/pdf", "teste.pdf");
}
}
}

Placing Images and Text in Specific (Absolute) Locations Using iTextSharp

I am generating a PDF using iTextSharp and there is dynamic content in the middle of the page which is pushing the bottom part of my PdfPTable down too far. Sometimes even off the bottom of the page onto another page.
Would it be possible to position the bottom PdfPTable in a way that it would not get pushed down when the table above it needs more vertical space?
Here is my solution.
Views\Home\Index.cshtml:
<h2>Create PDF</h2>
#Html.ActionLink("Create the PDF", "CreatePDF", "Home")
</div>
HomeController.cs:
public ActionResult Index()
{
return View();
}
public FileStreamResult CreatePDF()
{
Stream fileStream = GeneratePDF();
HttpContext.Response.AddHeader("content-disposition", "inline; filename=MyPDF.pdf");
var fileStreamResult = new FileStreamResult(fileStream, "application/pdf");
return fileStreamResult;
}
private Stream GeneratePDF()
{
var rect = new Rectangle(288f, 144f);
var document = new Document(rect, 10, 10, 10, 10);
document.SetPageSize(PageSize.LETTER.Rotate());
MemoryStream memoryStream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStream);
document.Open();
////////////////////////
//Place Image in a Specific (Absolute) Location
////////////////////////
Image myImage = Image.GetInstance(Server.MapPath("../Content/BI_logo_0709.png"));
myImage.SetAbsolutePosition(45, 45);
//[dpi of page]/[dpi of image]*100=[scale percent]
//72 / 200 * 100 = 36%
//myImage.ScalePercent(36f);
myImage.ScalePercent(36f);
document.Add(myImage);
////////////////////////
//Place Text in a Specific (Absolute) Location
////////////////////////
//Create a table to hold everything
PdfPTable myTable = new PdfPTable(1);
myTable.TotalWidth = 200f;
myTable.LockedWidth = true;
//Create a paragraph with the text to be placed
BaseFont bfArialNarrow = BaseFont.CreateFont(Server.MapPath("../Content/ARIALN.ttf"), BaseFont.CP1252, BaseFont.EMBEDDED);
var basicSmaller = new Font(bfArialNarrow, 10);
var myString = "Hello World!" +
Environment.NewLine +
"Here is more text." +
Environment.NewLine +
"Have fun programming!";
var myParagraph = new Paragraph(myString, basicSmaller);
//Create a cell to hold the text aka paragraph
PdfPCell myCell = new PdfPCell(myParagraph);
myCell.Border = 0;
//Add the cell to the table
myTable.AddCell(myCell);
//Add the table to the document in a specific (absolute) location
myTable.WriteSelectedRows(0, -1, 550, 80, pdfWriter.DirectContent);
pdfWriter.CloseStream = false;
document.Close();
memoryStream.Position = 0;
return memoryStream;
}

Bad size image in pdf created with itextsharp

I have a problem to create a pdf with itextsharp from images in .tiff.
Here is some code :
iTextSharp.text.Document d = new iTextSharp.text.Document();
PdfWriter pw = PdfWriter.GetInstance(d, new FileStream(filename, FileMode.Create));
d.Open();
PdfContentByte cb = pw.DirectContent;
foreach (Image img in imgs)
{
d.NewPage();
d.SetPageSize(new iTextSharp.text.Rectangle(0, 0, img.Width, img.Height));
iTextSharp.text.Image timg = iTextSharp.text.Image.GetInstance(img, iTextSharp.text.BaseColor.WHITE);
timg.SetAbsolutePosition(0, 0);
cb.AddImage(timg);
cb.Stroke();
}
d.Close();
It creates the pdf with two pages but the image on the first page is to big.The page have the size of the image but it zoom an the bottom left corner of the image.
It does that only with the tiff image, if I take png, it works fine.
Any solution?
Thanks to the comment of mkl, I found it.
Set the page size (SetPageSize) before the new page command (NewPage)
use like this
string[] validFileTypes = {"tiff"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = false;
if (!isValidFile)
{
Label.Text = "Invalid File. Please upload a File with extension " +
string.Join(",", validFileTypes);
}
else
{
string pdfpath = Server.MapPath("pdf");
Document doc = new Document(PageSize.A4, 0f, 0f, 0f, 0f);
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
doc.Open();
string savePath = Server.MapPath("images\\");
if (FileUpload1.PostedFile.ContentLength != 0)
{
string path = savePath + FileUpload1.FileName;
FileUpload1.SaveAs(path);
iTextSharp.text.Image tiff= iTextSharp.text.Image.GetInstance(path);
tiff.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);
tiff.SetAbsolutePosition(0,0);
PdfPTable table = new PdfPTable(1);
table.AddCell(new PdfPCell(tiff));
doc.Add(table);
}
doc.Close();
}

Categories

Resources