How to NOT flatten the image applied in a pdf with Itext in c#? - itext

I need to apply an image on all my pages from my PDF, but without flattening it ( I want to have the ability to move it in my PDF reader afterwards)
My code:
String basePath = "d:\\zPDF\\";
DirectoryInfo d = new DirectoryInfo(basePath);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.pdf"); //Getting Text files
List<string> listS = new List<string>();
foreach (FileInfo file in Files)
{
listS.Add(file.Name);
}
foreach (string s in listS)
{
using (System.IO.Stream inputPdfStream = new FileStream(basePath + s, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
//using (System.IO.Stream inputImageStream = new FileStream(basePath + "x1.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream inputImageStream2 = new FileStream(basePath + "x2.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream outputPdfStream = new FileStream(basePath + "zResult" + s, FileMode.Create, System.IO.FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
//stamper.FormFlattening = true;
//stamper.FreeTextFlattening = true;
int numberOfPages = reader.NumberOfPages;
Image myImage = Image.GetInstance(inputImageStream2);
float f-Image1, f-Image2;
for (int i = 1; i <= numberOfPages; i++)
{
int nr, plusMinus = 25;
Rectangle mediabox = reader.GetPageSize(i);
int getTOP = (int)mediabox.GetTop(0);
int getRight = (int)mediabox.GetRight(0);
var pdfContentByte = stamper.GetOverContent(i);
nr = getRight - 600;
f-Image1 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
nr = 40;
f-Image2 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
myImage.SetAbsolutePosition(f-Image1, f-Image2);
myImage.RotationDegrees = row1(-35, 35);
pdfContentByte.AddImage(myImage);
}
stamper.Close();
}
I've tried:
stamper.FormFlattening = false;
stamper.FreeTextFlattening = false;
but no results. The image is still flatten.
I think, after I've read some posts, that I need to set up my PdfStamper in useAppendMode() but I don't know how should I do this and, I don't know if this is this right direction.

Related

Vector Highlight Functionality is not working for Beider Morse Analyser in Lucene?

Vector Highlight functionality is not working properly when we use beider Morse Analyzer in lucene.NET. Anybody came across this issue?
Vector highlight is working fine for standard analyzer but it is not working properly for Beider morse. It is highlighting the entire string.
Directory directory = FSDirectory.GetDirectory("LuceneIndex");
Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
var tokenizer = new KeywordTokenizer(input: reader);
PhoneticEngine phoneticEngine = new PhoneticEngine(NameType.GENERIC, RuleType.APPROX, false);
var stream = new BeiderMorseFilter(input: tokenizer, phoneticEngine);
return new TokenStreamComponents(tokenizer, stream);
});
IndexWriter writer = new IndexWriter(directory, analyzer);
Document doc = new Document();
doc.Add(new Field("id", i.ToString(), Field.Store.YES, Field.Index.NO));
doc.Add(new Field("EmployeeName", text, Field.Store.YES, Field.Index.TOKENIZED));
writer.AddDocument(doc);
writer.Optimize();
writer.Flush();
writer.Close();
QueryParser queryParser = new QueryParser(Lucene.Net.Util.LuceneVersion.LUCENE_48, "EmployeeName", mAnalyzer);
IndexSearcher searcher = new IndexSearcher(directory);
Hits hits = searcher.Search(query);
int results = hits.Length();
Console.WriteLine("Found {0} results", results);
for (int i = 0; i < results; i++)
{
SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter();
Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(queryParser));
int totalScoreDocs = tTopDocs.ScoreDocs.Length > 30 ? 30 : tTopDocs.ScoreDocs.Length;
for (int i = 0; i < totalScoreDocs; i++)
{
int id = tTopDocs.ScoreDocs[i].Doc;
Document doc = searcher.Doc(id);
string text = doc.Get("EmployeeName");
TokenStream tokenStream = TokenSources.GetAnyTokenStream(mIndexSearcher.IndexReader, id, "EmployeeName", analyzer);
TextFragment[] frag = highlighter.GetBestTextFragments(
tokenStream, text, mergeContiguousFragments: false, maxNumFragments: 10); // highlighter.GetBestFragments(tokenStream, text, 3, "...");
for (int j = 0; j < frag.Length; j++)
{
if (frag[j] != null && frag[j].Score > 0)
{
Console.WriteLine(frag[j].ToString());
}
}
}
Sample For Lucene highlight
With Standard analyzer;
Input-John
Output-William <B>John<B> Russel
With Beider Morse analyzer;
Input-John
Output-<B>William John Russel<B>

Migrating add image to pdf from iText to PDFBox

In our project we are using iText 5.x version to manipulate PDF files and working to migrate that implementation with PDFBox 2.x version.
There is one add image to pdf page scenario and I have converted that code into PDFBox as good as I could do. :) In existing implementation(iText) they add image in template using PdfTemplate and added that template in annotation using PdfAnnotation class.
I don't know how to do that using PDFBox. Also please check that I migrated existing implementation properly or not as I'm newbie in PDF library using Java.
Add Image to PDF(Using iText):
Document document = null;
PdfReader pdfReader = null;
pdfReader = new PdfReader(SourceFilePath());
//we retrieve the total number of pages and the page size
int total = pdfReader.getNumberOfPages();
Rectangle rectangle = pdfReader.getPageSizeWithRotation(1);
document = new Document(rectangle);
PdfImportedPage page;
PdfCopy.PageStamp stamp;
// step 2: we create a PdfCopy object that listens to the document.
PdfCopy copy = new PdfCopy(document, new FileOutputStream(DestinationFilePath(false));
document.open();
// step 4: adding the content
for (int i = 1; i <= total; i++) {
page = copy.getImportedPage(pdfReader, i);
if(i == 1 || aBarcodeVO.getDisplacementVO().isApplyForAllPages()){
BufferedImage bufferedImage = getImage();
Image img = Image.getInstance(bufferedImage, null);
img.scaleToFit(qrImageSize, qrImageSize);
PdfName imgKey = new PdfName(aBarcodeVO.getImgUniqueId() + i);
Rectangle rectPage = pdfReader.getPageSizeWithRotation(i);
stamp = copy.createPageStamp(page);
PdfImage stream = new PdfImage(img, "", null);
stream.put(imgKey, imgKey);
PdfIndirectObject ref = copy.addToBody(stream);
int rotation = pdfReader.getPageRotation(i);
Rectangle cropBoxRect = pdfReader.getCropBox(i);;
//Explicitly Apply rotation to crop box rectangle.
for (int j = 0; j < (rotation/90); j++) {
cropBoxRect = cropBoxRect.rotate();
}
//added Image in template and template in Annotation and finally annotation is added in PDF through PdfCopy.PageStamp
PdfTemplate template = PdfTemplate.createTemplate(copy, img.getPlainWidth(), img.getPlainHeight());
img.setAbsolutePosition(0, 0);
img.setRotationDegrees(rotation);
img.setDirectReference(ref.getIndirectReference());
template.addImage(img);
Rectangle rect = new Rectangle(rectLlx, rectLly, rectUrx, rectUry);
rect.setBorderWidth(0.5f);
rect.setBorderColor(new BaseColor(0xFF, 0x00, 0x00));
PdfAnnotation annotation = PdfAnnotation.createStamp(copy, rect, null, "AnnotationOnly");
annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, template);
annotation.setFlags(PdfAnnotation.FLAGS_PRINT + PdfAnnotation.FLAGS_LOCKED);
annotation.setRotate(rotation);
PdfName annotKey = getAnnotKey(i);
annotation.put(annotKey, annotKey);
stamp.addAnnotation(annotation);
stamp.alterContents();
}
copy.addPage(page);
}
copy.freeReader(pdfReader);
try {
if (document != null) {
document.close();
}
} catch (Exception e) {
System.out.println("Exception in handleAddBarCode() while closing():document:" + e);
}
try {
if (pdfReader != null) {
pdfReader.close();
}
} catch (Exception e) {
System.out.println("Exception in handleAddBarCode() while closing():pdfReader:" + e);
}
Add Image to PDF(Using PDFBox):
PDDocument pdDocument = PDDocument.load(new File(SourceFilePath()));
int total = pdDocument.getNumberOfPages();
PDPage page = pdDocument.getDocumentCatalog().getPages().get(0);
PDRectangle rectangle = getRotatedMediaBox(page);
PDPage pdPage = new PDPage(rectangle);
PDDocument newDocument = new PDDocument();
for (int i = 0; i < total; i++) {
pdPage = newDocument.importPage(pdDocument.getPage(i));
PDRectangle pageRect = getRotatedMediaBox(pdPage);
int rotation = pdPage.getRotation();
PDRectangle cropBoxRect = page.getCropBox();
//Calculate margin between crop box rectangle and page rectangle.
float[] margins = getCropBoxMargin(pageRect, cropBoxRect, rotation);
if (rotation == 90 || rotation == 270) {
cropBoxRect = new PDRectangle(cropBoxRect.getLowerLeftY(), cropBoxRect.getLowerLeftX(), cropBoxRect.getHeight(),
cropBoxRect.getWidth());
}
BufferedImage bufferedImage = getImage();
PDPageContentStream pageContentStream = new PDPageContentStream(newDocument, pdPage,
PDPageContentStream.AppendMode.APPEND, true);
PDImageXObject image = JPEGFactory.createFromImage(newDocument, bufferedImage);
if (rotation == 90 || rotation == 270) {
Matrix matrix = Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0);
PDRectangle cropBox = pdPage.getCropBox();
float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
Rectangle rectang = cropBox.transform(matrix).getBounds();
float scale = Math.min(cropBox.getWidth() / (float)rectang.getWidth(), cropBox.getHeight() / (float)rectang.getHeight());
pageContentStream.transform(Matrix.getTranslateInstance(tx, ty));
pageContentStream.transform(matrix);
pageContentStream.transform(Matrix.getScaleInstance(scale, scale));
pageContentStream.transform(Matrix.getTranslateInstance(-tx, -ty));
}
pageContentStream.drawImage(image, rectLlx, rectLly, qrImageSize, qrImageSize);
pageContentStream.close();
}
newDocument.save(new File(DestinationFilePath(false)));
newDocument.close();
pdDocument.close();
Please help me on this or at least looking forward for your suggestions for code needs to rectify of PDFBox implementation.

Hundred thousands of datatable records to PDF in web API

I'm trying to create PDF from the DataTable in web api using ADO.Net. Unfortunately based on filters some times I may get very less records & able to download without any problem. Sometimes may be very huge like 200 thousand of records. When I'm checking in local my system its getting hang while converting the dt to PDF. My code is like below:
private FileContentResult ExportPDF(DataTable dataTable)
{
string Name = "Logs";
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
byte[] content = null;
try
{
string[] columnNames = (from dc in dataTable.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
int count = columnNames.Length;
object[] array = new object[count];
dataTable.Rows.Add(array);
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dataTable.Columns.Count;
int rows = dataTable.Rows.Count;
HeaderFooter header = new HeaderFooter(new Phrase(Name), false);
// Remove the border that is set by default
header.Border = iTextSharp.text.Rectangle.TITLE;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = Element.ALIGN_CENTER;
pdfDoc.Header = header;
// Header.
pdfDoc.Open();
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1; pdfTable.Width = 100;
pdfTable.Padding = 1; pdfTable.Spacing = 4;
//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Chunk chunkCols = new Chunk();
iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.Black);
chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);
}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
content = mStream.ToArray();
return File(content, "application/pdf", "LogReports.pdf");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Add Object To Other Object Scripts that require an Object

Ok , I have problem with adding object let's first see what is this about.
I Have Map when i click at map i create Sphere on map.
then i serialized the point, msg and name .....
void Start () {
Ser = new Serial();
Ser.read();
for (int i =0 ; i < Ser.list.Count; i++)
{
Data d = new Data();
d = Ser.list[i];
GameObject a = GameObject.CreatePrimitive(PrimitiveType.Sphere);
a.name = d.Id;
a.transform.position = new Vector3(d.x,d.y,0);
a.transform.localScale =new Vector3(0.5f , 0.5f , 0.5f);
Follow putTarget = new Follow();
Data Pos_In_File = new Data();
Pos_In_File = Ser.list[i];
GUIText GText = new GUIText();
Vector3 SP = new Vector3();
GameObject TextObj = new GameObject("GUIText" + Convert.ToString(i));
GText = (GUIText)TextObj.AddComponent(typeof(GUIText));
GText.text = Pos_In_File.msg;
GText.material.color = new Color(0 , 0 , 1);
GText.fontSize = 20;
GText.fontStyle = FontStyle.Bold;
SP = Camera.main.WorldToViewportPoint(new Vector3(Pos_In_File.x , Pos_In_File.y , Pos_In_File.z));
TextObj.transform.position = SP;
TextObj.AddComponent(typeof(Follow));
GameObject OBJ = GameObject.Find(Pos_In_File.Id);
putTarget =GetComponent<Follow>();
putTarget.target = OBJ.transform;
}
}
now in last three lines i want to add OBJ to TextOBJ->Follow(Script)->target
What i am messing up ?
i asked this quastion long ago my software have been finnished a 10 month
and the i get through this problem is
void Start () {
Resources.UnloadUnusedAssets();
Ser = new Serial();
Screen.fullScreen = true;
Ser.read();
for (int i =0 ; i < Ser.list.Count; i++)
{
Data d = new Data();
d = Ser.list[i];
GameObject a = GameObject.CreatePrimitive(PrimitiveType.Sphere);
a.name = d.Id;
a.transform.position = new Vector3(d.x,d.y,0);
a.renderer.material.color = Color.green;
Data Pos_In_File = new Data();
Pos_In_File = Ser.list[i];
GUIText GText = new GUIText();
Vector3 SP = new Vector3();
GameObject TextObj = new GameObject(Pos_In_File.Id+"h");
GText = (GUIText)TextObj.AddComponent(typeof(GUIText));
GText.text = Pos_In_File.msg;
GText.material.color = new Color(0 , 0 , 1);
GText.fontSize = 20 + (int)Camera.main.transform.position.z;
GText.fontStyle = FontStyle.Bold;
SP = Camera.main.WorldToViewportPoint(new Vector3(Pos_In_File.x , Pos_In_File.y , Pos_In_File.z));
TextObj.transform.position = SP;
TextObj.AddComponent(typeof(Follow));
}

Write Image on Text in PDF Form Fields using ITextSharp

When I tried to write an image on Text Field, the image is written behind text. It is working for normal text and image but not on Form Fields. I want to write image on Text that covers text behind.
void OldMethod()
{
string path = #"C:\Users\";
string OutLocation = path + "New.pdf";
string Old = path + "Old.pdf";
PdfReader reader1 = new PdfReader(Old);
using (FileStream fs = new FileStream(OutLocation, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
int pageCount1 = reader1.NumberOfPages;
//Create a new layer
for (int i = 1; i <= pageCount1; i++)
{
iTextSharp.text.Rectangle rect = reader1.GetPageSize(i);
PdfContentByte cb = stamper.GetOverContent(i);
AcroFields Fields = stamper.AcroFields;
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
Fields.SetField("Price", #"1323423345");
Fields.SetFieldProperty("Price", "TEXTCOLOR", BaseColor.RED, null);
string Img = path + "red_slash.jpg";
iTextSharp.text.Image jpeg = Image.GetInstance(System.Drawing.Image.FromFile(Img), ImageFormat.Jpeg);
float width = 100;
float height = 200;
jpeg.ScaleToFit(width, height);
jpeg.SetAbsolutePosition(210, 315);
cb.AddImage(jpeg);
}
}
}
}
Here I need to write the image on the field "Price"