I have a problem with regards on the page orientation of the paper size.
I have a pdf file which contains portrait and landscape page.
this code works perfectly.
string FileLocation = "c:\\Temp\\SomeFile.pdf";
string WatermarkLocation = "c:\\Temp\\watermark.gif";
Document document = new Document();
PdfReader pdfReader = new PdfReader(FileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
img.SetAbsolutePosition(250,300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)
PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
waterMark = stamp.GetUnderContent(page);
waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();
// now delete the original file and rename the temp file to the original file
File.Delete(FileLocation);
File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);
since I'm using absolute value to set the image position.
img.SetAbsolutePosition(250,300);
How can T set the image position if the page is landscape or portrait?
note: One pdf with landscape and portrait page orientation.
Is there by chance that I can use if statement?
if (//paper is landscape)
{
//code here
}
else
{
//code here
}
What do you want to achieve?
Normally, iText takes into account the value of the page rotation. This means that when a page is rotated, the coordinates will be rotated too.
If you want to overrule this, you can add this line:
stamper.RotateContents = false;
This is explained in Chapter 6 of my book. You can try this example to see the difference:
No rotation, text added normally: hello1.pdf
Rotation, text added normally ( = rotated): hello2.pdf
Rotation, text added with rotation ignored: hello3.pdf
Of course, this assumes that a rotation was defined for the pages. Sometimes, landscape is mimicked by defining a different page size instead of defining a rotation.
In that case, you should also read Chapter 6 because it explains how to get the MediaBox of a document. see the example PageInformation that introduces methods such as GetPageSize(), GetRotation() and GetPageSizeWithRotation().
This is all documented, but if it doesn't answer your question, please clarify. As demonstrated in the example, the rotation is taken into account by default when adding new content, so maybe I misunderstood the question.
Related
I am generating a pdf from others with IText7 in C# and I need to add information in a corner of each page automatically, I add the information but in some pages, the content occupies the entire page and I need the information to be left behind in those cases of the content, I attach the image of the result, thanks in advance
I am using a canvas and Div to add the text
PdfPage pag = pdfDocument.GetLastPage();
Canvas canvas = new Canvas(pag, pag.GetPageSize());
var div = new Div().SetMargin(0).SetPadding(0).SetKeepTogether(true);
div.SetFixedPosition(0, 0, pag.GetPageSize().GetWidth());
div.Add(new Paragraph("info").SetFontSize(12));
canvas.Add(div);
canvas.Close();
Sorry my English
result:
Pdf text added result
expected:
Pdf text added Expected
I have found the solution, I create a PDFCanvas and indicate that NewContentStreamBefore(), and it already adds the information behind the page
PdfPage pag = pdfDocument.GetLastPage();
PdfCanvas under = new PdfCanvas(pag.NewContentStreamBefore(), pag.GetResources(), pdfDocument);
Canvas canvas = new Canvas(under, pag.GetPageSize());
var div = new Div().SetMargin(0).SetPadding(0).SetKeepTogether(true);
div.SetFixedPosition(0, 0, pag.GetPageSize().GetWidth());
div.Add(new Paragraph("info").SetFontSize(12));
canvas.Add(div);
canvas.Close();
I have a very simple code that places the png image into PDF
Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 10);
string pathfile = ConfigurationManager.AppSettings["Temp_SaveLocation"];
string fileName = "SomeName.pdf";
path = pathfile + fileName;
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.Create));
pdfDoc.Open();
Image imghead = Image.GetInstance(templateFolder + "Letterhead.png");
imghead.SetAbsolutePosition(0, 0);
pdfDoc.Add(imghead);
pdfWriter.CloseStream = true;
pdfDoc.Close();
However, no matter what position for the image I set, that image ends up on a very bottom of a document. I even tried negative values for the absolute position. Nevertheless, the image stays on the very bottom of a document. How can I bring an image to a very top?
Thank you very much in advance
I found out that image will be to the top when this code is removed.
imghead.SetAbsolutePosition(0, 0);
I agree with K J. By setting imghead.SetAbsolutePosition(0, 0), you are setting your image to be at (X,Y) co-ordinate which is mostly lower left co-ordinate of the page.
Generally, lower-left corner of the page coincides with the origin of the coordinate system (0, 0). The upper-right corner of the page coincides with the coordinate (595, 842). You either remove or comment this method imghead.SetAbsolutePosition(0, 0) or adjust the Y co-ordinate of it to move the image towards the upper side of the page.
I'm trying to enlarge the icon of a PDF sticky note. Here's an image showing the sticky icon that I've stamped on the first page of the PDF for context:
I was under the impression the icon was guided by a rectangle that could be manipulated. Here's my code that has not been effective yet:
using (PdfStamper stamp = new PdfStamper(reader, fs))
{
PdfWriter attachment = stamp.Writer;
foreach (string file in files_to_attach)
{
PdfFileSpecification pdfAttch = PdfFileSpecification.FileEmbedded(attachment, file, file, null);
stamp.AddFileAttachment(file, pdfAttch);
}
//Create Note for first page
Rectangle rect = new Rectangle(850, 850, 650, 650);
PdfAnnotation annotation = PdfAnnotation.CreateText(stamp.Writer, rect, "TITLE OF NOTE", "Body text of the note", false, "Comment");
//Enlarge the Sticky Note icon
PdfDictionary page = reader.GetPageN(1);
PdfArray annots = page.GetAsArray(PdfName.ANNOTS);
PdfDictionary sticky = annots.GetAsDict(0);
PdfArray stickyRect = sticky.GetAsArray(PdfName.RECT);
PdfRectangle stickyRectangle = new PdfRectangle(
stickyRect.GetAsNumber(0).FloatValue - 50, stickyRect.GetAsNumber(1).FloatValue - 20,
stickyRect.GetAsNumber(2).FloatValue, stickyRect.GetAsNumber(3).FloatValue - 30);
sticky.Put(PdfName.RECT, stickyRectangle);
//Apply the Note to the first page
stamp.AddAnnotation(annotation, 1);
stamp.Close();
}
I thought I could change the float values and that would change the shape of the icon but so far it has not effected it all. Thank you for any suggestions.
You can't. The icon that is displayed for the "Comment" annotation is supplied by the viewer. The rect property is only used to define the lower left corner of where the icon gets placed on the page by the viewer. According to the PDF specification for annotations with the type "Text", "Conforming readers shall provide predefined icon appearances for at least the following standard names: Comment, Key, Note, Help, NewParagraph, Paragraph, Insert.
You can, however, create your own image, of any size, and use it as the appearance for a "Stamp" annotation. It can even look exactly like a "Comment" icon, just bigger. It would end up functioning in the same way for the end user.
According to this post (Removing Watermark from PDF iTextSharp) , #mkl code works fine for ExGstate graphical watermarks but I have tested this code to remove watermark from some files which have Text based watermarks behind PDF contents (like this file : http://s000.tinyupload.com/index.php?file_id=05961025831018336372)
I have tried multiple solutions that found in this site but get no success.
Can anyone help to remove this watermark types by changing above #mkl solution?
thanks
Just like in the case of the question the OP references (Removing Watermark from PDF iTextSharp), you can remove the watermark from your sample file by building upon the PdfContentStreamEditor class presented in my answer to that question.
In contrast to the solution in that other answer, though, we do not want to hide vector graphics based on some transparency value but instead the writing "Archive of SID" from this:
First we have to select a criterion to recognize the background text by. Let's use the fact that the writing is by far the largest here. Using this criterion makes the task at hand essentially the iTextSharp/C# pendant to this iText/Java solution.
There is a problem, though: As mentioned in that answer:
The gs().getFontSize() used in the second sample may not be what you expect it to be as sometimes the coordinate system has been stretched by the current transformation matrix and the text matrix. The code can be extended to consider these effects.
Exactly this is happening here: A font size of 1 is used and that small text then is stretched by means of the text matrix:
/NxF0 1 Tf
49.516754 49.477234 -49.477234 49.516754 176.690933 217.316086 Tm
Thus, we need to take the text matrix into account. Unfortunately the text matrix is a private member. Thus, we will also need some reflection magic.
Thus, a possible background remover for that file looks like this:
class BigTextRemover : PdfContentStreamEditor
{
protected override void Write(PdfContentStreamProcessor processor, PdfLiteral operatorLit, List<PdfObject> operands)
{
if (TEXT_SHOWING_OPERATORS.Contains(operatorLit.ToString()))
{
Vector fontSizeVector = new Vector(0, Gs().FontSize, 0);
Matrix textMatrix = (Matrix) textMatrixField.GetValue(this);
Matrix curentTransformationMatrix = Gs().GetCtm();
Vector transformedVector = fontSizeVector.Cross(textMatrix).Cross(curentTransformationMatrix);
float transformedFontSize = transformedVector.Length;
if (transformedFontSize > 40)
return;
}
base.Write(processor, operatorLit, operands);
}
System.Reflection.FieldInfo textMatrixField = typeof(PdfContentStreamProcessor).GetField("textMatrix", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
List<string> TEXT_SHOWING_OPERATORS = new List<string>{"Tj", "'", "\"", "TJ"};
}
The 40 has been chosen with that text matrix in mind.
Applying it like this
[Test]
public void testRemoveBigText()
{
string source = #"sid-1.pdf";
string dest = #"sid-1-noBigText.pdf";
using (PdfReader pdfReader = new PdfReader(source))
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(dest, FileMode.Create, FileAccess.Write)))
{
PdfContentStreamEditor editor = new BigTextRemover();
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
editor.EditPage(pdfStamper, i);
}
}
}
to your sample file results in:
I have a table and a chart to be added to a PDF Document. I have used the iTextSharpLibrary to add the contents to the PDF file.
Actually the problem is that the chart has a width of 1500px and the table fits in comfortably in an A4 page size.
Actually the chart image that I get must not be scaled to fit in the page as it reduces the viewability. Hence, I need to add a new page that has a wider width than the other ones or at least change the page orientation to landscape and then add the image. How do I do this?
This is the code that I used to add a new page and then resize the page and then add the image. This is not working. Any fixes?
var imageBytes = ImageGenerator.GetimageBytes(ImageSourceId);
var myImage = iTextSharp.text.Image.GetInstance(imageBytes);
document.NewPage();
document.SetPageSize(new Rectangle(myImage.Width, myImage.Height));
myImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
document.Add(myImage);
I fixed the Issue. I have to set the page size before calling the GetInstance of the Pdfdocument. Then, i can give different pagesizes for each page
I'm not sure what you mean by before calling the GetInstance of the Pdfdocument, but setting the pageSize right before calling newPage works.
Here follows the c# code to create a new pdf that's made of two pictures, no matter how wild their sizes difference is. The important lines here are the new Document and SetPageSize ones.
static public void MakePdfFrom2Pictures (String pic1InPath, String pic2InPath, String pdfOutPath)
{
using (FileStream pic1In = new FileStream (pic1InPath, FileMode.Open))
using (FileStream pic2In = new FileStream (pic2InPath, FileMode.Open))
using (FileStream pdfOut = new FileStream (pdfOutPath, FileMode.Create))
{
//Load first picture
Image image1 = Image.GetInstance (pic1In);
//I set the position in the image, not during the AddImage call
image1.SetAbsolutePosition (0, 0);
//Load second picture
Image image2 = Image.GetInstance (pic2In);
// ...
image2.SetAbsolutePosition (0, 0);
//Create a document whose first page has image1's size.
//Image IS a Rectangle, no need for new Rectangle (Image.Width, Image.Height).
Document document = new Document (image1);
//Assign writer
PdfWriter writer = PdfWriter.GetInstance (document, pdfOut);
//Allow writing
document.Open ();
//Get writing head
PdfContentByte pdfcb = writer.DirectContent;
//Put the first image on the first page
pdfcb.AddImage (image1);
//The new page will have image2's size
document.SetPageSize (image2);
//Add the new second page, and start writing in it
document.NewPage ();
//Put the second image on the second page
pdfcb.AddImage (image2);
//Finish the writing
document.Close ();
}
}