How to add image background to pdf for every page? - c#

I'm trying to set a background to a pdf and managed to set it with an image my pdf has a big table so the pages are added automatically not with the Document.NewPage() method so the image background is set only on the first page. This is the code that adds the background:
Image backImg = Image.GetInstance(#"D:\websites\DIS\bugs\130208\A4.png");
backImg.SetAbsolutePosition(0, 0);
backImg.Alignment = Image.UNDERLYING;
var doc = new Document(pageSize);
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
doc.Open();
doc.Add(backImg);
...
creating a big table
and not using the doc.NewPage() method. Do I have to loop throw every page and add the background image at the end before closing the doc, but how do I put it in the background not on top of the other elements?

Whenever you want to apply something to every page, you should use page events, more specifically PdfPageEvent.onEndPage(), to do it. You can find samples for its usage by keyword Page events > onEndPage --- these samples are taken from iText in Action 2nd Edition. The samples mainly add footers and headers while you want to add background graphics.
Be aware that you shouldn't add content to the Document instance here but instead directly to the PdfWriter, and as you want the image to be under the page content , not above it, you will need to use PdfWriter.getDirectContentUnder() like in the sample Stationery and not PdfWriter.getDirectContent() like in the other samples.
PS: The analogous samples for .Net can be found here.
PPS: The sample ImageDirect.java / ImageDirect.cs shows how to add an image to some direct content which might be the information missing here.

go for
PdfPageEvent.onStartPage()
. In this event, write your code to insert the image (as you are doing it). What it will do is that as soon as a new page is created, it will add the image to it and then the content over it; giving a watermark effect.

Related

PDFsharp PdfDocument.Save causing blank pages on any additional saves

While I have a workaround for this problem, I'd prefer to do it the way that I ran into this problem. Let me explain the context before getting to the problem:
I'm using a scanner to get virtual images which I want to use to create a PDF with each page being one single image. I got the working just fine using PDFsharp for creation of the PDF.
However; if I try to re-save the PDFsharp document, it ends up blanking all the previous pages, and then adding the new image.
For a little more context, I'm using ASP.NET Windows Forms, with NTwain for the scanning software, PDFsharp for creating the PDF, and PdfiumViewer to view the PDF on the Windows form.
I have a class-level variable for the document
PdfDocument document = new PdfDocument();
On image save, I simply save the image to a new page
var img = pictureBox1.Image;
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XImage image = XImage.FromGdiPlusImage(img);
gfx.DrawImage(image, 0, 0);
To render out the document, I copy the document (thought this might fix the problem) to a new document, save the contents to a new memory stream, and simply view the PDF
var viewDocument = (PdfDocument)document.Clone();
MemoryStream ms = new MemoryStream();
viewDocument.Save(ms, false);
ms.Position = 0;
var pdf = PdfiumViewer.PdfDocument.Load(ms);
pdfRenderer1.Load(pdf);
I got it working by saving the image to a list, instead of as a new page, and remade the document each time I wanted to display it. The issue is really strange, however.
Any help understanding why it does that is appreciated.
AFAIK this is the state of the implementation: The recommended way is to create a PdfDocument or open it from a file, make the changes you need, then save it once.
This is what you do in the implementation that works for you.
Saving the document, opening it, adding more pages, saving it again would also work. This way you would not need a list of all images. But IMHO using the list and creating a new PdfDocument each time you save is the cleanest way.
Unexpected results occur when saving again after further changes. This is a known issue. Feel free to investigate this issue and fix it. Maybe it is just a simple change, maybe it is complicated.

Adding a picture a predefined location with a placeholder into a existing pdf form.

Question Revised and clarified (Thanks to Bruno for point me in the right direction)-
This post was originally made under great sleep deprivation and after reading, I see how it could be confusing. I want to make sure that others have this solution in the future and not have to spend loads of time trying to figure it out.
Here is my question and there is an answer below that solves it.
I have a pdf form and I need to add an image to a specific location where I have put a place holder. How can I do this?
Just for future people who may be looking for the answer on how to best add an image to a pre-defined specific location into a pre-existing .pdf form, here is the answer.
/* This codes works for those who have a pre-created pdf form with a button in the location and size you want your image.
I reccomend acrobat pro, thought it has a monthly cost. There are additional free PDF editors
instantiate a new PdfStamper that will create a new file from my existing form. The Reader reads in your template and the stamper makes a copy
FileToPath and FileFromPath are strings i created above that hold the path
*/
using (PdfStamper stamper = new PdfStamper(new PdfReader(fileFromPath), File.Create(FileToPath)))
{
//get my buttons positions current location and height btn1 is the name of my button that exists in the pdf already
AcroFields.FieldPosition fieldPosition = stamper.AcroFields.GetFieldPositions("btn1")[0];
//create a new button utilze the field position to set it's location. FYI this is a rectangle. I reccomend you read about those
//it will save you tons of time to understand them.
PushbuttonField imageField = new
//btn1Replaced is what I named the new button that will overwrite the old place holder button
PushbuttonField(stamper.Writer, fieldPosition.position, "btn1Replaced");
//Here I set they layout from my old button to my new one
imageField.Layout = PushbuttonField.LAYOUT_ICON_ONLY;
//grab the image you want in your pdf imgPath is a string I wrone above to grab the image
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("imgPath");
//set your buttons image property to be your image you just grabbed
imageField.Image = img;
//always scale to the size of the button
imageField.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
imageField.ProportionalIcon = false;
//make sure your button is read only and then it will not act like a button, it will act like an image.
imageField.Options = BaseField.READ_ONLY;
//Get rid of the old button
stamper.AcroFields.RemoveField("btn1");
//add my button and make sure it is on the correct page
stamper.AddAnnotation(imageField.Field, fieldPosition.page);
stamper.Close();
}

Take image of div in ASP.net

I am trying to make T-shirt design website. User customize its t-shirt by putting diffrent div and image over t-shirt div which has t-shirt in background using jquery now after final customization I want to save the picture of t-shirt/div so I can save customization.
How can i save customization div into image?
You can use the html2canvas library that can render to "canvas" your div and then make it image send it back to you.
You can get the code, and see examples here.
http://html2canvas.hertzen.com/
Here is the conversion from canvas to image for get it back:
http://www.nihilogic.dk/labs/canvas2image/
My Concerns.
What if a javascript error appears and the user lose whats make of ?
What if user not use a new modern browser that can handle the "canvas" so that can render to image whats inside the div.
The other way is to use flash and some programming on flash.
Ideally, you'll want to use server side processing to generate your images- rather than a DOM-based approached. You may want to consider using GDI+. Something along these lines should get you started (assuming the context of an ASP.NET page):
tshirt.aspx
var imagePath1 = #"C:\path\to\tshirt.jpg";
var imagePath2 = #"C:\path\to\graphic.jpg";
var bg = new Bitmap(imagePath1);
var overlay = new Bitmap(imagePath2);
var gfx = Graphics.FromImage(bg);
gfx.DrawImage(overlay, new Point(50, 50));
Response.ContentType="image/jpeg"
bg.Save(Response.OutputStream, ImageFormat.Jpeg);
Then on the page where the image is needed:
<img src="tshirt.aspx" />
Using the same code above for "tshirt.aspx", you can replace the call to bg.Save(Stream, ImageFormat) with bg.Save(filePath, ImageFormat) to write the generated image to disk.

How to display a PdfPage as image in WPF form using Docotic.pdf.dll

I need to display PdfPage of a PDF Document in a WPF form. I am using Docotic.pdf.dll and want to stick to it. The PdfPage.Thumbnail is also giving me null with all PDFs.
Just confirmed from Bit Miracle, this feature has been added in Docotic.Pdf 3.4 (available on their site) and currently it is in beta phase .
Below is the code that will save the image from the Pdf.
using (PdfDocument pdf = new PdfDocument("your_file.pdf"))
{
PdfDrawOptions options = PdfDrawOptions.CreateZoom(150);
options.BackgroundColor = new PdfRgbColor(255, 255, 255); // white background, transparent by default
options.Format = PdfDrawFormat.Jpeg;
pdf.Pages[0].Save("result.jpg", options);
}
There is also Draw and print PDF group of samples that might worth to look into.
As far as I know Docotic.Pdf cannot display PDF files (at least the current version), it can only create them. The PdfPage.Thumbnail refers to the page thumbnail embedded in the PDF file, which usually is missing, this is why the property returns null.

Render HTML as an Image

I'm generating a coupon based on dynamic input and a cropped image, and I'm displaying the coupon using ntml and css right now, the problem is, printing this has become an issue because of how backgrounds disappear when printing and other problems, so I think the best solution would be to be able to generate an image based on the html, or set up some kind of template that takes in strings and an image, and generates an image using the image fed in as a background and puts the coupon information on top.
Is there anything that does this already?
This is for an ASP.NET 3.5 C# website!
Thanks in advance.
edit: It'd be great if the output could be based on the HTML input, as the coupon is designed by manipulating the DOM using jQuery and dragging stuff around, it all works fine, it's just when it comes to the printing (to paper) it has z-indexing issues.
What you can do is create an aspx page that changes the response type to be in the format you want and then put the image into the stream. I created a barcode generator that does a similar thing. Excluding all the formalities of generating the image, you'll Page_Load will look something like this:
Bitmap FinalBitmap = new Bitmap();
MemoryStream msStream = new MemoryStream();
strInputParameter == Request.Params("MagicParm").ToString()
// Magic code goes here to generate your bitmap image.
FinalBitmap.Save(msStream, ImageFormat.Png);
Response.Clear();
Response.ContentType = "image/png";
msStream.WriteTo(Response.OutputStream);
if ((FinalBitmap != null)) FinalBitmap.Dispose();
and that's it! Then all you have to do in your image is set the URL to be something like RenderImage.aspx?MagicParm=WooHoo or whatever you need. That way you can have it render whatever you want to specify.
You can render html to a bitmap using the WebBrowser control in either a winforms or console application.
An example of this can be found here: http://www.wincustomize.com/articles.aspx?aid=136426&c=1
The above example can be modified to run in ASP.Net by creating a new STAThread and performing an Application.Run on it to start a new message loop.
PHP/Ruby Alternative
If you have accessed this question and are actually looking for soething that will work without Windows, you can try the KHTML library: http://wiki.goatpr0n.de/projects/khtmld
The website has a ridiculous name I admit, but I can assure you it is genuine. Other related pages are: the sourceforge page http://khtml2png.sourceforge.net/
Try PDFSharp...it's not exactly a "take this HTML and make a PDF" but with a small amout of fiddling you can easily make a PDF out of the info you are using to make the HTML.
MARKUP ONLY ALTERNATE SOLUTION
Use SVG and XSLT to transform the html data into an image that can be rendered/saved/etc.
I'll admit that at first it was tedious getting this to work because of all of the coordinates, but well worth the effort once it is running.
There is a very powerful image creation library called GD which I often use with PHP.
I am led to believe there is a wrapper for this library that ASP programmers can use. Try this
Unless the "other problems" are pretty severe, couldn't you just instruct your users to turn on Background Images when printing?
In any case, I'd default to serving a PDF rather than an image, doubly so since it is intended for print.
Just set up your css properly, so that you have a css file targeted at the print medium. It is pretty easy to guarantee that the coupon will always be legible, without worrying about whether they have bg images on or not. Needlesly moving to an image doesn't make any sense, unless there is some reason you don't want it to be machine readable.
I haven't tried to myself, but you should be able to render HTML into an image by using the WebBrowser control and the DrawToBitmap() method inherited from the base Control class.
UPDATE: I tried this myself and there are some caveats. The WebBrowser control doesn't seem to render the web page until the control is show, so the WebBrowser needs to be in a Form and the Form must be shown for the HTML to be rendered and the DocumentCompleted event to be raised.

Categories

Resources