How to mimic watermark in excel using softartisans ExcelWriter? If so do we have any sample code for it? - officewriter

Sample Code:
ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Create();
Worksheet ws = wb.Worksheets[0];
Shapes shps = ws.Shapes;
Anchor anch = ws.CreateAnchor(0, 7, 0, 0);
Shape shpHeart = shps.CreateShape(ShapeType.TextBox, anch);
shpHeart.FillTransparency=0.5;

As you know, Excel doesn't have the concept of a watermark. The problem with adding a shape or image to a worksheet is that it will float over the cells. If you want something to appear behind the cells, the best way is to put a large image in the header or footer, as described in this MS article: http://office.microsoft.com/en-us/excel-help/mimic-a-watermark-in-excel-HP010103239.aspx
To do this programmatically with the ExcelWriter API, you can use the SetContent method of the HeaderFooterSection object. You can also adjust dimensions of the image with the HeaderFooterPicture object.
Example:
ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Create(ExcelApplication.FileFormat.Xlsx);
Worksheet sheet1 = wb.Worksheets[0];
PageSetup pgsetup = sheet1.PageSetup;
HeaderFooterSection centerFooter = pgsetup.GetFooter(HeaderFooterSection.Section.Center);
string watermarkImagePath = #"C:\images\watermark.jpg";
using (FileStream fs = File.Open(watermarkImagePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//Note: Excel requires including the "&G" code when inserting
//an image in a header or footer
centerFooter.SetContent("&G",fs);
}
xla.Save(wb, Page.Response, "watermarktest.xlsx", false);
More information about formatting headers and footers: http://wiki.softartisans.com/display/EW8/Formatting+Headers+and+Footers

Related

itext 7 c# how to clip an existing pdf

let's say I have a bunch of pdf files that I want to migrate into a new pdf. BUT the new pdf file is a table-structured file. And the content of the pdf files should fit in the first cell of a two-column-table.
I am not sure if the approach of working with tables is correct. I am open to any other solutions. All I want is at the end some custom text at the top, followed by pdf content and a checkbox on the right side. (One per pdf content)
What I have so far:
`
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc, PageSize.A4);
doc.SetMargins(0f, 0f, 18f, 18f);
PdfReader reader = new PdfReader(src);
PdfDocument srcDoc = new PdfDocument(reader);
Table table = new Table(new float[] { 2f, 1f });
PdfFormXObject imagePage = srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc);
var image = new Image(imagePage);
Cell cell = new Cell().Add(image);
cell.SetHorizontalAlignment(HorizontalAlignment.LEFT);
cell.SetVerticalAlignment(VerticalAlignment.TOP);
table.AddCell(cell);
Table checkTable = new Table(2);
Cell cellCheck1 = new Cell();
cellCheck1.SetNextRenderer(new CheckboxCellRenderer(cellCheck1, "cb1", 0));
cellCheck1.SetHeight(50);
checkTable.AddCell(cellCheck1);
Cell cellCheck2 = new Cell();
cellCheck2.SetNextRenderer(new CheckboxCellRenderer(cellCheck2, "cb2", 1));
cellCheck2.SetHeight(50);
checkTable.AddCell(cellCheck2);
table.AddCell(checkTable);
doc.Add(table);
doc.Close();`
My Problem here is that the pdf content has still its margin. Which completely spoils the design. It is so frustrating, I appreciate any help.
You say
My Problem here is that the pdf content has still its margin. Which completely spoils the design.
PDFs (usually) don't know anything about margins. Thus, you have to detect the margins of the page to import first. You can do this by parsing the page content into an event listener that keeps track of the bounding box of drawing instructions, like the TextMarginFinder. Then you can reduce the source page to those dimensions. This can be done by means of the following method:
PdfPage restrictToText(PdfPage page)
{
TextMarginFinder finder = new TextMarginFinder();
new PdfCanvasProcessor(finder).ProcessPageContent(page);
Rectangle textRect = finder.GetTextRectangle();
page.SetMediaBox(textRect);
page.SetCropBox(textRect);
return page;
}
You apply this method in your code right before you copy the page as form XObject, i.e. you replace
PdfFormXObject imagePage = srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc);
by
PdfFormXObject imagePage = restrictToText(srcDoc.GetFirstPage()).CopyAsFormXObject(pdfDoc);
This causes the Image this XObject will be embedded in to have the correct size. Unfortunately it will be somewhat mispositioned because the restricted page still has the same coordinate system as the original one, merely its crop box defines a smaller section than before. To fix this, one has to apply an offset, one has to subtract the coordinates of the lower left corner of the page crop box which has become the XObject bounding box. Thus, add after instantiating the Image the following code:
Rectangle bbox = imagePage.GetBBox().ToRectangle();
image.SetProperty(Property.LEFT, -bbox.GetLeft());
image.SetProperty(Property.BOTTOM, -bbox.GetBottom());
image.SetProperty(Property.POSITION, LayoutPosition.RELATIVE);
Now the restricted page is properly positioned in your table cell.
Beware: The TextMarginFinder (as its name indicates) determines the margins by text alone. Thus, if the page contains other contents, too, e.g. decorations like a logo, this logo is ignored and might eventually be cut out. If you want such decorations, too, in your overviews, you have to use a different margin finder class.

iTextSharp automatically shrinking images when end of the page reach

I'm using iTextSharp to display images in a pdf report. Here I want display two images in a row and it's working as expected but having a issue when end of the page reaches. The issue is that last row images get shrink to fit in same page, it doesn't automatically add it to the next page. All images having same dimension and resolution.
Please, provide us with the code.
I wrote the test below (although it's in java, there should be no problem) and the results seem to be correct.
public void tableWithImagesTest01() throws IOException, InterruptedException {
String testName = "tableWithImagesTest01.pdf";
String outFileName = destinationFolder + testName;
String cmpFileName = sourceFolder + "cmp_" + testName;
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
Document doc = new Document(pdfDoc, PageSize.A3);
Image image1 = new Image(ImageDataFactory.create(sourceFolder + "itis.jpg"));
Table table = new Table(2);
for (int i = 0; i < 20; i++) {
table.addCell(new Cell().add(image1));
table.addCell(new Cell().add(image1));
table.addCell(new Cell().add(new Paragraph("Hello")));
table.addCell(new Cell().add(new Paragraph("World")));
}
doc.add(table);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
The result pdf looks like this:
Maybe you use summat image1.setAutoScale(true);? Still we need your code to look at.
The easiest solution (considering all images have the same dimension and resolution) would be to manually insert a new page and pagebreak every time you have inserted the maximum number of images to a page.
Taken from a comment below, the solution that works is, on the individual images you need to set:
image.ScaleToFitHeight = false;
Likely to happen when keeping rows together

Add itextsharp barcode image to PdfPCell

I'm trying generate barcodes from a text string and then PDF the results using iTextSharp. Right now, I have the code below:
// Create a Document object
var pdfToCreate = new Document(PageSize.A4, 0, 0, 0, 0);
// Create a new PdfWrite object, writing the output to a MemoryStream
var outputStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(pdfToCreate, outputStream);
PdfContentByte cb = new PdfContentByte(pdfWriter);
// Open the Document for writing
pdfToCreate.Open();
PdfPTable BarCodeTable = new PdfPTable(3);
// Create barcode
Barcode128 code128 = new Barcode128();
code128.CodeType = Barcode.CODE128_UCC;
code128.Code = "00100370006756555316";
// Generate barcode image
iTextSharp.text.Image image128 = code128.CreateImageWithBarcode(cb, null, null);
// Add image to table cell
BarCodeTable.AddCell(image128);
// Add table to document
pdfToCreate.Add(BarCodeTable);
pdfToCreate.Close();
When I run this and try to open the PDF programmatically, I receive an error saying "The document has no pages."
However when I use:
pdfToCreate.Add(image128);
(instead of adding to a table, I add it to a cell), the barcode shows up (though it's floating off the document).
I'd like to send the barcodes to a table so that I can format the document easier. The final product will be 20-60 barcodes read from a database. Any idea on where I'm going wrong?
You are telling the PdfPTable constructor to create a three column table but only providing one of the columns:
PdfPTable BarCodeTable = new PdfPTable(3);
iTextSharp by default ignores incomplete rows. You can either change the constructor to match your column count, add the extra cells or call BarCodeTable.CompleteRow() which will fill in the blanks using the default cell template.

adding page numbers and creating landscape A4 in streams with itext

I have the following code that generates a pdf into the stream. This works well but i now have the following requirements.
1) make page landscape: Looking at other examples they add the property to the document object. But i'm doing this instream. So how would i add this property?
2) Add page numbers. I need to put items into a grid so that there are x number of rows per page. With a page number at the footer of the page. How can this kind of feature be acheived with Itext sharp.
public static void Create(ICollection<Part> parts, string path)
{
PdfReader reader = new PdfReader(path);
var pageWidth = 500;
byte[] bytes;
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
PdfContentByte cb = stamper.GetOverContent(1);
//Flush the PdfStamper's buffer
stamper.Close();
//Get the raw bytes of the PDF
bytes = ms.ToArray();
var now = String.Format("{0:d-M-yyyy}", DateTime.Now);
var pdfName = string.Format("{0}_factory_worksheet", now).Replace("%", "").Replace(" ", "_");
var context = HttpContext.Current;
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "attachment;filename=" + pdfName);
context.Response.Buffer = true;
context.Response.Clear();
context.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
context.Response.OutputStream.Flush();
context.Response.End();
}
}
}
I don't really know how you handling it C# but logical flow will be like this:
Use PdfDictionary to rotate content in reader to 90 degree.Assuming your pdf contain multiple pages,
PdfReader reader = new PdfReader(path);
for (int pgCnt=1; pgCnt <= reader.getNumberOfPages(); pgCnt++) {
//Logic to implement rotation & Add Page number
}
To get current rotation(assuming you are using Portrait mode & try to convert it in landscape mode) use int rttnPg = reader.getPageRotation(pgCnt); also get the PdfDictionary of that page pgDctnry=reader.getPageN(i);(I named that variable as pgDctnry)
Now to rotate it in 90 degree use
pgDctnry.put(PdfName.ROTATE, new PdfNumber(rttnPg+90));
Now bind it using PdfStamper as you are currently doing it.Now to add page number get over content(here i named it pgCntntBt) of the current page
pgCntntBt = stamper .getOverContent(pgCnt);
rctPgSz = rdrPgr.getPageSizeWithRotation(pgCnt);
pgCntntBt.beginText();
bfUsed=//Base Font used for text to be displayed.Also set font size pgCntntBt.setFontAndSize(bfUsed,8.2f);
txtPg=String.format(pgTxt+" %d/%d",pgCnt,totPgCnt);
pgCntntBt.showTextAligned(2,txtPg,//Put Width,//Put Height,//Rotation);
pgCntntBt.endText();
Actually i don't understand what you mean by this:"I need to put items into a grid so that there are x number of rows per page. With a page number at the footer of the page".Now close the stamper to flush it in outputstream.

Using PDF itextSharp it is possible to put an image on top of text while creating the pdf document

I attempted several ways to do this, but still cannot get it.
It appears iTextSharp requires a 2 pass situation so that an image appears on top of the text.
So I am attempting to do this using memory streams, but I keep getting errors.
Public Function createDoc(ByRef reqResponse As HttpResponse) As Boolean
Dim m As System.IO.MemoryStream = New System.IO.MemoryStream()
Dim document As Document = New Document()
Dim writer As PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, m)
document.Open()
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Close()
writer.Flush()
writer.Flush()
'yes; I get the pdf if this is the last statement
'reqResponse.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length)
'this statment does not work it says the stream is closed
'm.Position = 0
Dim Reader As PdfReader = New PdfReader(m)
'Dim rm As MemoryStream = New MemoryStream(m.GetBuffer(), 0, m.GetBuffer().Length)
Dim PdfStamper As PdfStamper = New PdfStamper(Reader, reqResponse.OutputStream)
Dim cb As iTextSharp.text.pdf.PdfContentByte = Nothing
cb = PdfStamper.GetOverContent(1)
Dim locMyImage As System.Drawing.Image = System.Drawing.Image.FromStream(zproProduceWhiteImageToCovertBarCodeNumbers())
Dim BImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(locMyImage, iTextSharp.text.BaseColor.CYAN)
Dim overContent As PdfContentByte = PdfStamper.GetOverContent(1)
BImage.SetAbsolutePosition(5, 5)
overContent.AddImage(BImage)
PdfStamper.FormFlattening = True
PdfStamper.Close()
'rm.Flush()
'rm.Close()
'Dim data As Byte() = rm.ToArray()
'reqResponse.Clear()
'Dim finalMs As MemoryStream = New MemoryStream(data)
'reqResponse.ContentType = "application/pdf"
'reqResponse.AddHeader("content-disposition", "attachment;filename=labtest.pdf")
'reqResponse.Buffer = True
'finalMs.WriteTo(reqResponse.OutputStream)
'reqResponse.End()
'Dim data As Byte() = rm.ToArray()
'reqResponse.OutputStream.Write(data, 0, data.Length)
''Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
''Response.OutputStream.Flush();
''Response.OutputStream.Close();
''Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest()
Return True
End Function
reference:
Put text on top of an image?
seach engine reference:
whiteout text on a pdf document by using a image which is the same color as the background pdf
image overlap with itextpdf
itextsharp image on top of the text whiteout
itextsharp place picture on top of text
itextpdf image on top
thanks,
Doug Lubey of Louisiana
You can do this pretty easily. The Document object is a helper object that abstracts away many of the internals of the PDF model and for the most part assumes that you want to flow content and that text would go above images. If you want to get around this you can talk directly the PdfWriter object instead. It has two properties, DirectContent and DirectContentUnder that both have methods named AddImage() that you can use to set an absolute position on an image. DirectContent is above existing content and DirectContentUnder is below it. See the code for an example:
You appear to be doing this on the web so you'll need to adapt this to whatever stream you are using but that should be pretty easy.
One note, NEVER call GetBuffer() on a MemoryStream, ALWAYS use ToArray(). The former method includes uninitialized bytes that will give you potentially corrupt PDFs.
''//File that we are creating
Dim OutputFile As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
''//Image to place
Dim SampleImage As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SampleImage.jpg")
''//Standard PDF creation setup
Using FS As New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
Using Doc As New Document(PageSize.LETTER)
Using writer = PdfWriter.GetInstance(Doc, FS)
''//Open the document for writing
Doc.Open()
''//Add a simple paragraph
Doc.Add(New Paragraph("Hello world"))
''//Create an image object
Dim Img = iTextSharp.text.Image.GetInstance(SampleImage)
''//Give it an absolute position in the top left corner of the document (remembering that 0,0 is bottom left, not top left)
Img.SetAbsolutePosition(0, Doc.PageSize.Height - Img.Height)
''//Add it directly to the raw pdfwriter instead of the document helper. DirectContent is above and DirectContentUnder is below
writer.DirectContent.AddImage(Img)
''//Close the document
Doc.Close()
End Using
End Using
End Using