Dynamically Insert Image to PDF using LiveCycle/ITextSharp - c#

I have a pdf template I created using LiveCycle Designer. Inside it, I have 3 Image Fields that I created, ImageField1, ImageField2, ImageField3. The images are located on a url, let's call it "http://images.com/img/IMAGENAME.jpg", and the user selects the images prior to generating the pdf in which case I store the image names in a string array.
Is it possible to add these images programmatically into the Image Fields? The methods I've tried so far have only lead to a corrupted pdf that won't open at all.
public string Foo(int id)
{
try
{
var file = string.Empty;
var property = ((IRepositoryBase)PropertyRepository).GetById<Property>(id);
var purchase = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyPurchase>(id);
var inspection = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyInspection>(id);
file = HttpContext.Current.Server.MapPath("\\Assets\\documents\\originals\\Brochure.pdf");
var tmp = HttpContext.Current.Server.MapPath("\\Assets\\documents\\temps\\");
tmp += string.Format("{0}-Brochure.pdf", property.Id);
var pdfReader = new PdfReader(file);
var pdfStamper = new PdfStamper(pdfReader, new FileStream(tmp, FileMode.Create));
var pdfFormFields = pdfStamper.AcroFields;
var pht = property.BrochurePhoto;
string[] photos = pht.Split(' ');
PdfContentByte cB = new PdfContentByte(pdfStamper.Writer);
if (photos[0] != null)
{
iTextSharp.text.Image photoToPdf1 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[0].ToString() + ".jpg"));
cB.AddImage(photoToPdf1);
}
if (photos[1] != null)
{
iTextSharp.text.Image photoToPdf2 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[1].ToString() + ".jpg"));
cB.AddImage(photoToPdf2);
}
if (photos[2] != null)
{
iTextSharp.text.Image photoToPdf3 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[2].ToString() + ".jpg"));
cB.AddImage(photoToPdf3);
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
return string.Format("{0}-Brochure.pdf", property.Id);
}
catch (Exception ex)
{
Log.Error(ex);
return string.Empty;
}
}

Related

Read PDF Line By Line using iText7 and Fill on Textboxes Winforms

I am working on a WinForms application. I use the pdf file to reset the password and the values on pdf are stored as key-value pairs(email: xxxx#mail.com, pass: 11111).
What I want to do:
Read the PDF file line by line and fill the appropriate textboxes.
What I Have done:
public bool CreatePDF(string location, string email, string key)
{
if(location != "" && email != "" && key != "")
{
PdfWriter pdfwriter = new PdfWriter(location);
PdfDocument pdf = new PdfDocument(pdfwriter);
Document document = new Document(pdf);
Paragraph fields = new Paragraph("Email: "+email + "\n" + "Secret Key: "+key);
document.Add(fields);
document.Close();
return true;
}
else
{
return false;
}
}
public string ReadPDF(string location)
{
var pdfDocument = new PdfDocument(new PdfReader(location));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
return text;
}
}
Thank you in advance Guys!. Any suggestions on CreatePDF are also welcome.
This is what I came up with,
var pdfDocument = new PdfDocument(new PdfReader("G:\\Encryption_File.pdf"));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
text.Split('\n');
string line = "";
line = text + "&";
string[] newLines = line.Split('&');
textBox1.Text = newLines[0].Split(':')[1].ToString();
textBox2.Text = newLines[0].Split(':')[2].ToString();

Perform OCR via MODI on specific region instead of entire document

I am trying to get to perform bulk OCR on images in a selected directory via MODI. Here's the code.
private void button1_Click(object sender, EventArgs e) {
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
InitialDirectory = "C:\\Users",
IsFolderPicker = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
invoicePath = dialog.FileName;
CheckFileAndDoOCR(imageDirectory);
}
}
public string CheckFileAndDoOCR(string directoryPath) {
string TheTxt = "";
IEnumerator files = Directory.GetFiles(directoryPath).GetEnumerator();
while (files.MoveNext()) {
FileInfo foo = new FileInfo(Convert.ToString(files.Current));
if (foo.Extension == ".jpg" || foo.Extension == ".JPG") {
TheTxt = DoOCR(foo.FullName);
string txtFileName = foo.DirectoryName + "\\" + foo.Name.Replace(foo.Extension, "") + ".txt";
FileStream createFile = new FileStream(txtFileName, FileMode.OpenOrCreate);
StreamWriter writeFile = new StreamWriter(createFile);
writeFile.Write(TheTxt);
writeFile.Close();
createFile.Close();
}
try {
foo.Delete();
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return TheTxt;
}
public string DoOCR(string FullPath) {
MODI.Document miDoc;
MODI.Word miWord;
MODI.IMiRects miRects;
MODI.IMiRect miRect;
string strRectInfo;
miRect = null;
string txt;
string word;
MODI.Document md = new MODI.Document();
md.Create(FullPath);
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);
MODI.Image image = (MODI.Image)md.Images[0];
txt = image.Layout.Text;
word = null;
image = null;
md.Close(false);
md = null;
GC.Collect();
GC.WaitForPendingFinalizers();
return txt;
}
How can I perform the OCR on a specific area, for example
Rectangle Area = new Rectangle() {
X = 1367,
Y = 420,
Height = 57,
Width = 411
};
I have to extract data from one region/rectangle only from all the images. How can I do that? I have tried IronOCR and Tesseract, works like a charm. But I have been told to use MODI. Please help.

convert a jpg/png/txt or any file format to pdf using mvc5

How do i convert a jpg/png/txt or any file format to pdf using mvc c#.
Here is the code:
public ActionResult SaveProfileDocument(string code)
{
bool isSavedSuccessfully = true;
string fName = "";
string _documentname = String.Empty;
try
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Documents\\Profile\\" + code, Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString());
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
_documentname=fName;
var path = string.Format("{0}\\{1}", pathString, file.FileName);
if (System.IO.File.Exists(path)) {
_documentname=Guid.NewGuid()+"_"+file.FileName;
var path2 = string.Format("{0}\\{1}", pathString,_documentname );
file.SaveAs(path2);
}
else {
file.SaveAs(path);
}
}
}
}
catch (Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName, documentname = _documentname });
}
else
{
return Json(new { Message = "Error in saving file", documentname=""});
}
}
In the above code i am saving the file.but
here i need to convert the file and then save.
so for convert i need a separate class or method here only call that method.
The thing is that while upload a file inthat time need to convert pdf any file to convert pdf. and save in folder or whatever.
can't convert an image file to PDF. You can create a PDF file and add the image file to it:
string pdfpath = Server.MapPath("PDFs");
string imagepath = Server.MapPath("Images");
Document doc = new Document();
try
{
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
doc.Open();
doc.Add(new Paragraph("GIF"));
Image gif = Image.GetInstance(imagepath + "/mikesdotnetting.gif");
doc.Add(gif);
}
catch (Exception ex)
{
//Log error;
}
finally
{
doc.Close();
}
here i am refer:
https://www.mikesdotnetting.com/article/87/itextsharp-working-with-images

c# Printing a PDF with iTextSharp

I have a problem with printing a pdf.
So my Document is being created by writing some values in a pdf document and saving it
public void CreateDocument(string name)
{
string oldreport = #"..\Resources\FehlerReport.pdf";
string newreportpath = #"..\Resources\" + name;
using (var newFileStream = new FileStream(newreportpath, FileMode.Create))
{
var pdfReader = new PdfReader(oldreport);
var stamper = new PdfStamper(pdfReader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
form.SetField("Auftragsnummer", Kundeninformation.Auftragsnummer.ToString());
form.SetField("Kundensachnummer", Kundeninformation.Kundensachnummer.ToString());
form.SetField("Kundenname", Kundeninformation.Kundenname.ToString());
form.SetField("Kundenbestellnummer", Kundeninformation.Kundenbestellnummer.ToString());
form.SetField("Kundenrezepturnummer", Kundeninformation.Kundenrezepturnummer.ToString());
form.SetField("Spulennummer", Kundeninformation.Spulennummer.ToString());
form.SetField("Fertigungsdatum1", System.DateTime.Today.ToString("dd.MM.yy"));
int i = 1;
foreach (var item in _MeasurementReport.MeasurementReportItems)
{
form.SetField(("UhrzeitRow" + i).ToString(), item.Uhrzeit.ToString("HH:mm:ss"));
form.SetField(("FehlerindexRow" + i).ToString(), i.ToString());
form.SetField(("Position mmRow" + i).ToString(), (item.Laufmeter * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("HoeheRow" + i).ToString(), (item.DefectCountours.H * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Breite mmRow" + i).ToString(), (item.DefectCountours.W * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Flaeche Row" + i).ToString(), (item.DefectCountours.W * pixelSize * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
i++;
}
form.SetField("Datum", System.DateTime.Today.ToString("dd.MM.yy"));
form.SetField("Uhrzeit", System.DateTime.Now.ToString("HH:mm"));
stamper.FormFlattening = true;
stamper.Close();
pdfReader.Close();
}
}
So now i want to print the document with this function, which also calls the CreateDocument function. It prints, but the paper is white. I checked if the created pdf is being created, and it is being created but apparently not printed.
public void Print()
{
string name = Kundeninformation.Auftragsnummer + "_" + Kundeninformation.Spulennummer+".pdf";
CreateDocument(name);
List<string> PrinterFound = new List<string>();
PrinterSettings printer = new PrinterSettings();
foreach (var item in PrinterSettings.InstalledPrinters)
{
PrinterFound.Add(item.ToString());
}
printer.PrinterName = PrinterFound[7];
printer.PrintFileName = name;
PrintDocument PrintDoc = new PrintDocument();
PrintDoc.DocumentName = #"..\Resources\"+name;
PrintDoc.PrinterSettings.PrinterName = PrinterFound[7];
PrintDoc.Print();
}
make sure your file is created completely.. otherwise you will this issue. to test quickly put some delay between file creation and printing

ABCpdf only rendering first page

When I try to save each page as GIF using ABCpdf, only the first page is saved.
For example: I have a PDF that has 3 pages. I use ABCpdf to render each page to a stream, which is saved to disk. When I open the files in my destination folder, all 3 files show the first page content.
Here's my code:
using (Doc theDoc = new Doc())
{
XReadOptions options = new XReadOptions { ReadModule = ReadModuleType.Pdf };
theDoc.Read(inputbytearray, options);
using (MemoryStream ms = new MemoryStream())
{
theDoc.Rendering.DotsPerInch = 150;
int n = theDoc.PageCount;
for (int i = 1; i <= n; i++)
{
Guid FileName = Guid.NewGuid();
theDoc.Rect.String = theDoc.CropBox.String;
theDoc.Rendering.SaveAppend = (i != 1);
theDoc.Rendering.SaveCompression = XRendering.Compression.G4;
theDoc.PageNumber = i;
theDoc.Rendering.Save(string.Format("{0}.gif", FileName), ms);
using (var streamupload = new MemoryStream(ms.GetBuffer(), writable: false))
{
_BlobStorageService.UploadfromStream(FileName.ToString(), streamupload, STR_Gif, STR_Imagegif);
}
}
// theDoc.Clear();
}
}
The Rendering.SaveAppend property is only applicable when saving TIFF images. For GIFs you would need to save a separate image for each PDF page.
private void button1_Click(object sender, System.EventArgs e)
{
string theDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\files\";
// Create test PDF
using (Doc doc = new Doc())
{
for (int i = 1; i <= 3; i++)
{
doc.Page = doc.AddPage();
doc.AddHtml("<font size=24>PAGE " + i.ToString());
}
doc.Save(Path.Combine(theDir, "test.pdf"));
}
// Save PDF pages to GIF streams
using (Doc doc = new Doc())
{
doc.Read(Path.Combine(theDir, "test.pdf"));
for (int i = 1; i <= doc.PageCount; i++)
{
doc.PageNumber = i;
doc.Rect.String = doc.CropBox.String;
using (MemoryStream ms = new MemoryStream())
{
doc.Rendering.Save("dummy.gif", ms);
using (FileStream fs = File.Create(Path.Combine(theDir, "p" + i.ToString() + ".gif")))
{
ms.Seek(0, SeekOrigin.Begin);
ms.CopyTo(fs);
}
}
}
}
}

Categories

Resources