How to use " in CodeDom Source Code? - c#

I want to append this Line to the source code which will be compiled :
Temp.AppendLine(#"[assembly: AssemblyDescription("[DESCRIPTION]"]);");
But you see the [DESCRIPTION] is not in the string too...
Instead of the [DISCRIPTION] I want to use the input of an TextBox. How can I do that?
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog d = new SaveFileDialog();
d.Filter = "Executable (*.exe)|*.exe";
if (d.ShowDialog() == DialogResult.OK)
{
String InputCode = String.Empty;
String regcode = String.Empty;
//Unser TestCode, in dem Wir ein MessageBox aufrufen
InputCode = "MessageBox.Show((1 + 2 + 3).ToString());";
System.CodeDom.Compiler.CodeDomProvider CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
//Parameter für die Compilierung, wie die einzubindenen Bibliotheken usw.
System.CodeDom.Compiler.CompilerParameters CompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
CompilerParameters.ReferencedAssemblies.Add("System.dll");
CompilerParameters.OutputAssembly = d.FileName;
CompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CompilerParameters.CompilerOptions += "/target:winexe" + " " + "/win32icon:" + "\"" + textBox6.Text + "\"";
CompilerParameters.GenerateExecutable = true;
CompilerParameters.GenerateInMemory = false;
//Über den StringBuilder wird der Code zusammengesetzt
StringBuilder Temp = new StringBuilder();
Temp.AppendLine(#"using System;");
Temp.AppendLine(#"using System.Windows.Forms;");
Temp.AppendLine(#"using System.Diagnostics;");
Temp.AppendLine(#"namespace RunTimeCompiler{");
Temp.AppendLine(#"public class Test{");
Temp.AppendLine(#"public static void Main(){");
Temp.AppendLine(#InputCode);
Temp.AppendLine(#"}");
Temp.AppendLine(#"public void Ergebnis(){");
Temp.AppendLine(#"}}}");
//Compilieren
System.CodeDom.Compiler.CompilerResults CompilerResults = CodeDomProvider.CompileAssemblyFromSource(CompilerParameters, Temp.ToString());
//Auf CompilerFehler prüfen
if (CompilerResults.Errors.Count > 0)
{
MessageBox.Show(CompilerResults.Errors[0].ErrorText, "Fehler bei Laufzeitkompilierung", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("Done", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

Take the TextBox input, convert it to a C# string literal and place it within the string that contains the attribute code:
string description = textBox1.Text;
string descriptionAsCsharpStringLiteral =
"#\"" + description.Replace("\"", "\"\"") + "\"";
string attribute =
"[assembly: AssemblyDescription(" + descriptionAsCsharpStringLiteral + ")]";
Temp.AppendLine("using System.Reflection;")
.AppendLine(attribute)
.AppendLine("namespace ...");

Related

Reading encoded string from DataGridView in c#

I am having problems with reading Korean characters from datagridview. I read korean alphabets from csv and written them to datagridview. My method is as follows:
int encoder = 949;
public void DisplayPCM()
{
StreamReader sr;
Encoding korean = Encoding.GetEncoding(encoder);
string selectedDirectory = projectPath + "\\Spec";
string filePath = selectedDirectory + "\\" + functionfile;
pcmpath = new StringBuilder(filePath);
if (Directory.Exists(selectedDirectory))
{
if (File.Exists(filePath))
{
try
{
sr = new StreamReader(filePath, korean);
int lineCount = 0;
StringBuilder readLine = new StringBuilder(sr.ReadLine());
while (readLine.ToString() != null && readLine.ToString() != "")
{
string[] substr = readLine.ToString().Split(',');
if (lineCount >= 1)
{
dPCM.Rows[lineCount - 1].Cells[0].Value = substr[0];
dPCM.Rows[lineCount - 1].Cells[1].Value = substr[1];
dPCM.Rows[lineCount - 1].Cells[2].Value = substr[2];
dPCM.Rows[lineCount - 1].Cells[3].Value = substr[3];
}
readLine = new StringBuilder(sr.ReadLine());
lineCount++;
}
sr.Close();
}
catch
{
MessageBox.Show("Error in Part File \n" + filePath);
}
}
else
{
MessageBox.Show(filePath + "\n does not exist.");
}
}
else
{
}
}
Until this point, there are no problems. The characters in datagridview are displayed in korean alphabets.
Now i have to edit the text in datagridview and read back the text and save it in csv file and reload this csv file text to datagridview.
When I did this procedure, I get some chinese text. It looks like when reading the string from datagridview, there is a problem. For reading datagridview text and saving it in csv file, my steps are as follows:
private void Save_PCM()
{
DirectoryInfo di;
StreamWriter sw = null;
int rowcount = 0;
StringBuilder Newnum, NewName, Newlower, Newupper;
try
{
Encoding korean = Encoding.GetEncoding(encoder);
string selectedDirectory = projectPath + "\\Spec";
string filePath = selectedDirectory + "\\" + functionfile;
pcmpath = new StringBuilder(filePath);
sw = new StreamWriter(pcmpath.ToString());
sw.WriteLine("NO,NAME,Lower SPEC,Upper SPEC");
while (dPCM.Rows[rowcount].Cells[0].Value != null)
{
Newnum = new StringBuilder(dPCM.Rows[rowcount].Cells[0].Value.ToString());
NewName = new StringBuilder(dPCM.Rows[rowcount].Cells[1].Value.ToString());
Newlower = new StringBuilder(dPCM.Rows[rowcount].Cells[2].Value.ToString());
Newupper = new StringBuilder(dPCM.Rows[rowcount].Cells[3].Value.ToString());
if (Newnum == null || NewName == null || Newlower == null || Newupper == null)
break;
sw.WriteLine(Newnum + "," + NewName + "," + Newlower + "," + Newupper);
rowcount++;
}
sw.Close();
}
catch (IOException e)
{
MessageBox.Show("Project name error" + Environment.NewLine + e.Message);
}
catch (NullReferenceException e)
{
MessageBox.Show("Enter all values in PCM" + Environment.NewLine + e.Message);
}
finally
{
if (sw != null)
sw.Close();
}
}
I think that I have to read datagridview cell values by including some encoding methods but I am clueless.
How can I read the text encoded in korean language from datagridview. Thanks in advance.
Now it looks like it works. I thought that the problem was in reading the encoded text from datagridview but the problem was in writing the encoded text to csv file. I made changes in function to read the data into .csv file. I declared a filestream path and added the filestream path and encoding to the streamwriter.
private void Save_PCM()
{
DirectoryInfo di;
FileStream stream = null;
StreamWriter sw = null;
int rowcount = 0;
StringBuilder Newnum, NewName, Newlower, Newupper;
try
{
Encoding korean = Encoding.GetEncoding(encoder);
string selectedDirectory = projectPath + "\\Spec";
string filePath = selectedDirectory + "\\" + functionfile;
pcmpath = new StringBuilder(filePath);
stream = new FileStream(pcmpath.ToString(), FileMode.Create); // overwrite existing file
sw = new StreamWriter(stream, korean);
sw.WriteLine("NO,NAME,Lower SPEC,Upper SPEC");
while (dPCM.Rows[rowcount].Cells[0].Value != null)
{
Newnum = new StringBuilder(dPCM.Rows[rowcount].Cells[0].Value.ToString());
byte[] bb = korean.GetBytes(dPCM.Rows[rowcount].Cells[1].Value.ToString());
NewName = new StringBuilder(Encoding.Default.GetString(bb));
Newlower = new StringBuilder(dPCM.Rows[rowcount].Cells[2].Value.ToString());
Newupper = new StringBuilder(dPCM.Rows[rowcount].Cells[3].Value.ToString());
if (Newnum == null || NewName == null || Newlower == null || Newupper == null)
break;
sw.WriteLine(Newnum + "," + NewName + "," + Newlower + "," + Newupper);
rowcount++;
}
sw.Close();
}
catch (IOException e)
{
MessageBox.Show("Project name error" + Environment.NewLine + e.Message);
}
catch (NullReferenceException e)
{
MessageBox.Show("Enter all values in PCM" + Environment.NewLine + e.Message);
}
finally
{
if (sw != null)
sw.Close();
}
}

Path is still unusable after use of streamreader even though streamreader was closed

UPDATE: I have saved the path in a string and sent it over to the other document,
I have made a small game for school and everything works as intended, but when the "ITAMons" (that's how we call them) level up an if statement is accessed and a streamwriter is trying to write onto a file which was used by a streamreader before, but the streamreader was closed and still it says I can't access the file, because it's still in use.
The StreamReaders are defined in the document itself and here they get defined and then used in the ITAMon constructor
sr = new StreamReader(Zielordner.Text + "\\" + ITAListe.CheckedItems[0].ToString());
sr2 = new StreamReader(Zielordner.Text + "\\" + ITAListe2.CheckedItems[0].ToString());
ITAMon1 = new ITAMon(sr);
ITAMon2 = new ITAMon(sr2);
which has at the end of it sr.Close().
Here's the entire constructor:
public ITAMon(StreamReader sr)
{
ITAName = sr.ReadLine();
if (ITAName == String.Empty)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
string[] Auslesung = sr.ReadLine().Split(';');
if (Auslesung.Length > 6)
{
switch (Auslesung[0])
{
case "Feuer":
Element = Element.Feuer;
break;
case "Wasser":
Element = Element.Wasser;
break;
case "Pflanze":
Element = Element.Pflanze;
break;
default:
Element = Element.Normal;
break;
}
Level = Convert.ToInt32(Auslesung[1]);
Leben = Convert.ToDouble(Auslesung[2]);
CurrentLife = Leben;
EXP = Convert.ToInt32(Auslesung[3]);
Look = Auslesung[4];
BaseDmg = Convert.ToInt32(Auslesung[5]);
Verteidigung = Convert.ToDouble(Auslesung[6]);
Geschwindigkeit = Convert.ToDouble(Auslesung[7]);
Erweitert = true;
}
else if (Auslesung.Length < 7)
{
switch (Auslesung[0])
{
case "Feuer":
Element = Element.Feuer;
break;
case "Wasser":
Element = Element.Wasser;
break;
case "Pflanze":
Element = Element.Pflanze;
break;
default:
Element = Element.Normal;
break;
}
Level = Convert.ToInt32(Auslesung[1]);
Leben = Convert.ToDouble(Auslesung[2]);
CurrentLife = Leben;
EXP = Convert.ToInt32(Auslesung[3]);
Look = Auslesung[4];
Erweitert = false;
}
string[] Attacke1 = sr.ReadLine().Split(';');
if (Attacke1.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[0] = new Attacke(Attacke1[0], Convert.ToInt32(Attacke1[1]), Convert.ToInt32(Attacke1[3]), Convert.ToInt32(Attacke1[2]));
string[] Attacke2 = sr.ReadLine().Split(';');
if (Attacke2.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[1] = new Attacke(Attacke2[0], Convert.ToInt32(Attacke2[1]), Convert.ToInt32(Attacke2[3]), Convert.ToInt32(Attacke2[2]));
string[] Attacke3 = sr.ReadLine().Split(';');
if (Attacke3.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[2] = new Attacke(Attacke3[0], Convert.ToInt32(Attacke3[1]), Convert.ToInt32(Attacke3[3]), Convert.ToInt32(Attacke3[2]));
string[] Attacke4 = sr.ReadLine().Split(';');
if (Attacke4.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[3] = new Attacke(Attacke4[0], Convert.ToInt32(Attacke4[1]), Convert.ToInt32(Attacke4[3]), Convert.ToInt32(Attacke4[2]));
sr.Close();
}
Despite the sr.Close() it still says the path in use when this if statement is accessed and a streamwriter is trying to use the path.
if (ITAMon1.CrtLife <= 0 || ITAMon1.GetAttacken[0].Mgz == 0 & ITAMon1.GetAttacken[1].Mgz == 0 & ITAMon1.GetAttacken[2].Mgz == 0 & ITAMon1.GetAttacken[3].Mgz == 0)
{
Pfad = Zielordner.Text + "\\" + ITAListe2.CheckedItems[0].ToString();
EventLog.Text = ITAMon2.GetName + " Gewinnt!";
ITAMon2.GetEXP += ITAMon2.GetGegner.GetLevel;
if(ITAMon2.LvlUp())
{
Gewinner = ITAMon2;
MessageBox.Show(ITAMon2.GetName + " hat das nächste Level erreicht!", "LevelUp", MessageBoxButtons.OK, MessageBoxIcon.Information);
LevelUp levelUp = new LevelUp();
levelUp.Show();
}
else
{
ITAMon2.Save(Pfad);
srG.Close();
this.Close();
MessageBox.Show(ITAMon2.GetName + " Gewinnt!", "Gewinner", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else if (ITAMon2.CrtLife <= 0 || ITAMon2.GetAttacken[0].Mgz == 0 & ITAMon2.GetAttacken[1].Mgz == 0 & ITAMon2.GetAttacken[2].Mgz == 0 & ITAMon2.GetAttacken[3].Mgz == 0)
{
Pfad = Zielordner.Text + "\\" + ITAListe.CheckedItems[0].ToString();
EventLog.Text = ITAMon1.GetName + " Gewinnt!";
ITAMon1.GetEXP += ITAMon1.GetGegner.GetLevel;
if (ITAMon1.LvlUp())
{
Gewinner = ITAMon1;
MessageBox.Show(ITAMon1.GetName + " hat das nächste Level erreicht!", "LevelUp", MessageBoxButtons.OK, MessageBoxIcon.Information);
LevelUp levelUp = new LevelUp();
levelUp.Show();
}
else
{
srG = new StreamWriter(Pfad);
ITAMon1.Save(Pfad);
srG.Close();
this.Close();
MessageBox.Show(ITAMon1.GetName + " Gewinnt!", "Gewinner", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Does anybody have any ideas how to fix that? It should be usable, even after I manually wrote sr.Close() into the document itself and it still wouldn't work, any help would be appreciated.

c# generate hocr file using charlesw tesseract

how can i generate hocr using the tesseract wrapper here
currently i need to dynamically add the location of the tessdata to the environment variables and run my code
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + #"\tesseract-3.05.00dev-win32-vc19\tesseract.exe";
string inputImg = #"00067.jpg";
string hocrLocation = #"00067";
string argsPdf = "\"" + inputImg + "\"" + " " + "\"" + hocrLocation + "\"" + " hocr ";
Console.WriteLine(argsPdf);
pProcess.StartInfo.Arguments = argsPdf;
pProcess.StartInfo.CreateNoWindow = false;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.Start();
string strOutput = pProcess.StandardOutput.ReadToEnd();
Console.WriteLine("OUtput: " + strOutput);
pProcess.WaitForExit();
and then i found the tesseract wrapper. how can i generate an hocr file using the wrapper? i cant find an example how to do it.
this is the current code(from the example ) im using but how to output an hocr file?
var testImagePath = "./phototest.tif";
if (args.Length > 0)
{
testImagePath = args[0];
}
try
{
using (var engine = new TesseractEngine(#"./tessdata", "eng", EngineMode.Default))
{
using (var img = Pix.LoadFromFile(testImagePath))
{
using (var page = engine.Process(img))
{
}
}
}
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
Console.WriteLine("Unexpected Error: " + e.Message);
Console.WriteLine("Details: ");
Console.WriteLine(e.ToString());
}
string hocrText = page.GetHOCRText(pageNum - 1);

writing a logfile when backgroundWorker job completed

I have c# application where it displays a message on messagebox after the query is run.At the sametime I want it to write a logfile. This is what i tried but no luck. My logfile was empty.
It had created a empty file.
private void backgroundWorker_Import_DoWork(object sender, DoWorkEventArgs e)
{
//Finally, loop through each row in the dataView and execute INSERT Statements against database
int recCount = 0;
successCount = 0;
failedCount = 0;
dv.RowFilter = "execute_bit IN ('1')";
using (MySqlConnection connectionMySql = new MySqlConnection(connectionStringMySql))
{
connectionMySql.Open();
MySqlCommand commandMySql = new MySqlCommand();
commandMySql.Connection = connectionMySql;
foreach (DataRowView rowView in dv)
{
recCount++;
backgroundWorker_Import.ReportProgress(recCount);
commandMySql.CommandText = rowView["sql"].ToString();
try
{
successCount = successCount + commandMySql.ExecuteNonQuery();
//WriteToLogFile("");
//WriteToLogFile("");
**WriteToLogFile(DateTime.Now.ToString() + ", " + recCount.ToString() + "," + successCount.ToString() + "," + failedCount.ToString());
}**
catch (Exception)
{
failedCount++;
}
}
}
}
private void backgroundWorker_Import_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string msg = "";
msg = msg + "Records successfully imported: " + successCount.ToString() + Environment.NewLine;
msg = msg + "Records that failed to import: " + failedCount.ToString() + Environment.NewLine + Environment.NewLine;
msg = msg + "Records excluded from import (20 minute grace-period): " + (tblVehicles.Rows.Count - successCount - failedCount).ToString();
progressBar1.Visible = false;
MessageBox.Show( msg, "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
**private void WriteToLogFile(string[] output)
{
StreamWriter sw = null;
FileStream fs = null;
string logfileFileName = System.IO.Path.Combine( "C:/luvi/logfile.txt");
fs = File.Open(logfileFileName, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
foreach (string line in output)
{
sw.WriteLine(line);
}
sw.Close();
sw = null;
}**
You could use File.WriteAllLines as shown in this topic.
Its' syntax is as follows:
public static void WriteAllLines(
string path,
string[] contents
)
In your case you would use it like so:
string logfileFileName = #"C:/luvi/logfile.txt";
File.WriteAllLines(logfileFileName, output);
Note: this overwrites the file, if you want to append them use File.AppendAllLines.
You need to actually call your method aswell, which may be a problem because I do not see that in your code. In the following changes I have replaced the string msg for an array, and added those (you could also use a list and call list.Add).
private void backgroundWorker_Import_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string[] msg = new string[] {};
msg[0] = "Records successfully imported: " + successCount.ToString();
msg[1] = "Records that failed to import: " + failedCount.ToString();
msg[2] = "Records excluded from import (20 minute grace-period): " + (tblVehicles.Rows.Count - successCount - failedCount).ToString();
// Write to log!
WriteToLogFile(msg);
// Show to messagebox.
string showmsg = msg[0] + Environment.NewLine + msg[1] + Environment.NewLine + msg[2];
progressBar1.Visible = false;
MessageBox.Show(showmsg, "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void WriteToLogFile(string[] output)
{
string logfileFileName = "C:/luvi/logfile.txt";
File.AppendAllLines(logfileFileName, output);
}
it seem problem with WriteToLogFile( string[] output) method. You are passing single string while it is expecting arrary of string. catch block is failing it silently.

Images extracted from pdf file is inverted/negative image.(C#)

Hi i am working on pdf to xhtml conversion using pdf clown library(C#).I am extracting the pdf content,the images which i extracted is inverted image.I want the real images,please any suggestions?..
The code is pasted below,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using it.stefanochizzolini.clown.documents;
using it.stefanochizzolini.clown.files;
using it.stefanochizzolini.clown.documents.contents;
using it.stefanochizzolini.clown.documents.contents.objects;
using it.stefanochizzolini.clown.tools;
using it.stefanochizzolini.clown.documents.contents.composition;
using it.stefanochizzolini.clown.documents.contents.fonts;
using System.IO;
using it.stefanochizzolini.clown.bytes;
using it.stefanochizzolini.clown.objects;
namespace Test1
{
public partial class Form1 : Form
{
public int index;
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files|*.pdf";
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnProcess_Click(object sender, EventArgs e)
{
InitiateProcess(txtFileName.Text.Trim());
}
private void InitiateProcess(string FileName)
{
it.stefanochizzolini.clown.files.File file;
Document document;
try
{
// Open the PDF file!
file = new it.stefanochizzolini.clown.files.File(FileName);
// Get the PDF document!
document = file.Document;
//file.Dispose();
}
catch
{
MessageBox.Show("Sorry. Error in File");
return;
}
//Page stamper is used to draw contents on existing pages.
PageStamper stamper = new PageStamper();
foreach (Page page in document.Pages)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + "\nScanning page " + (page.Index + 1) + "...\n";
stamper.Page = page;
// Wraps the page contents into a scanner.
Extract(new ContentScanner(page), stamper.Foreground, page );
stamper.Flush();
this.Refresh();
}
}
private void Extract(ContentScanner level, PrimitiveFilter builder, Page page)
{
string ctype = string.Empty;
if (level == null)
return;
while (level.MoveNext())
{
ContentObject content = level.Current;
//TextExtractor extractor = new TextExtractor();
string aa = content.GetType().ToString();
/*if(content is Text)
{
txtOutput.Text = txtOutput.Text + aa + Environment.NewLine;
List<ITextString> textStrings = extractor.Extract(page)[TextExtractor.DefaultArea];
foreach(ITextString textstring in textStrings)
{
RectangleF textstringbox=textstring.Box.Value;
txtOutput.Text = txtOutput.Text + "x:" + Math.Round(textstringbox.X);
txtOutput.Text = txtOutput.Text + "y:" + Math.Round(textstringbox.Y) + ",";
txtOutput.Text = txtOutput.Text + "w:" + Math.Round(textstringbox.Width) + ",";
txtOutput.Text = txtOutput.Text + "h:" + Math.Round(textstringbox.Height);
txtOutput.Text=txtOutput.Text+ "]: " + textstring.Text.ToString();
}
}*/
if (content is Text)
{
ContentScanner.TextWrapper text = (ContentScanner.TextWrapper)level.CurrentWrapper;
//ContentScanner.GraphicsState test = level.getState();
foreach (ContentScanner.TextStringWrapper textString in text.TextStrings)
{
RectangleF rf = (RectangleF)textString.Box;
/*txtOutput.Text = txtOutput.Text + Environment.NewLine + "Text [font size: " + textString.Style.FontSize + " ],[font Name: " +
textString.Style.Font.Name + " ]: " + textString.Text + "[position = left :" + rf.Left.ToString() + " & Top: " + rf.Top.ToString() + "X:" + rf.X.ToString() + "Y:" + rf.Y.ToString();*/
txtOutput.Text = txtOutput.Text + Environment.NewLine + textString.Text;
}
}
//else if (content is MarkedContent)
//{
// //MarkedContent mc = (MarkedContent) content
//}
else if (content is ShowText)
{
it.stefanochizzolini.clown.documents.contents.fonts.Font font = level.State.Font;
txtOutput.Text = txtOutput.Text + (font.Decode(((ShowText)content).Text));
}
else if (content is ContainerObject)
{
// Scan the inner level!
Extract(level.ChildLevel, builder, page);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.InlineImage)
{
ContentScanner.InlineImageWrapper img = (ContentScanner.InlineImageWrapper)level.CurrentWrapper;
ExportImage(
img.InlineImage.Body.Value,
txtOutputPath.Text.Trim() + System.IO.Path.DirectorySeparatorChar + "ImageExtractionSample_" + (index++) + ".jpg"
);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.GraphicsObject)
{
/*=============================================================================
* TO EXTRACT THE GRAPHICAL OBJECT WITHIN THE PDF
=============================================================================*/
ContentScanner.GraphicsObjectWrapper objectWrapper = level.CurrentWrapper;
if (objectWrapper == null)
{
continue;
}
/*
NOTE: Images can be represented on a page either as
external objects (XObject) or inline objects.
*/
SizeF? imageSize = null; // Image native size.
/*if (objectWrapper is PdfDataObject)
{
ContentScanner.GraphicsObjectWrapper gobjectwrapper=(ContentScanner.GraphicsObjectWrapper)gobjectwrapper;
it.stefanochizzolini.clown.objects.PdfDataObject pdobjt=gobjectwrapper
}*/
//if(objectWrapper is Image)
//{
// }
if (objectWrapper is ContentScanner.XObjectWrapper)
{
ContentScanner.XObjectWrapper xObjectWrapper = (ContentScanner.XObjectWrapper)objectWrapper;
it.stefanochizzolini.clown.documents.contents.xObjects.XObject Xobject = xObjectWrapper.XObject;
// Is the external object an image?
if (Xobject is it.stefanochizzolini.clown.documents.contents.xObjects.ImageXObject)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine +
"External Image '" + xObjectWrapper.Name + "' (" + Xobject.BaseObject + ")"; // Image key and indirect reference.
imageSize = Xobject.Size; // Image native size.
PdfDataObject dataObject = Xobject.BaseDataObject;
;
PdfDictionary header = ((PdfStream)dataObject).Header;
if (header.ContainsKey(PdfName.Type) && header[PdfName.Type].Equals(PdfName.XObject) && header[PdfName.Subtype].Equals(PdfName.Image))
{
if (header[PdfName.Filter].Equals(PdfName.Image)) // JPEG image.
{
// Get the image data (keeping it encoded)!
IBuffer body1 = ((PdfStream)dataObject).GetBody(false);
//object h1 = PdfName.ColorSpace;
// Export the image!
ExportImage(
body1,
txtOutputPath.Text + System.IO.Path.DirectorySeparatorChar + "Image_" + (index++) + ".png"
);
}
}
}
else if (content is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
Dictionary<RectangleF?, List<ITextString>> textStrings = null;
PageAnnotations annotations = page.Annotations;
TextExtractor extractor = new TextExtractor();
if (annotations == null)
{
Console.WriteLine("No annotations here.");
continue;
}
foreach (it.stefanochizzolini.clown.documents.interaction.annotations.Annotation annotation in annotations)
{
if (annotation is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
if (textStrings == null)
{ textStrings = extractor.Extract(page); }
it.stefanochizzolini.clown.documents.interaction.annotations.Link link = (it.stefanochizzolini.clown.documents.interaction.annotations.Link)annotation;
RectangleF linkBox = link.Box;
StringBuilder linkTextBuilder = new StringBuilder();
foreach (ITextString linkTextString in extractor.Filter(textStrings, linkBox))
{ linkTextBuilder.Append(linkTextString.Text); }
string bb = linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + "Link '" + linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + " Position: "
+ "x:" + Math.Round(linkBox.X) + ","
+ "y:" + Math.Round(linkBox.Y) + ","
+ "w:" + Math.Round(linkBox.Width) + ","
+ "h:" + Math.Round(linkBox.Height);
}
}
}
else if (objectWrapper is ContentScanner.InlineImageWrapper)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + "Inline Image";
InlineImage inlineImage = ((ContentScanner.InlineImageWrapper)objectWrapper).InlineImage;
imageSize = inlineImage.Size; // Image native size.
}
if (imageSize.HasValue)
{
RectangleF box = objectWrapper.Box.Value; // Image position (location and size) on the page.
txtOutput.Text = txtOutput.Text + Environment.NewLine +
" on page " + (page.Index + 1) + " (" + page.BaseObject + ")"; // Page index and indirect reference.
txtOutput.Text = txtOutput.Text + Environment.NewLine + " Coordinates:";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " x: " + Math.Round(box.X);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " y: " + Math.Round(box.Y);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " width: " + Math.Round(box.Width) + " (native: " + Math.Round(imageSize.Value.Width) + ")";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " height: " + Math.Round(box.Height) + " (native: " + Math.Round(imageSize.Value.Height) + ")";
}
/*=============================================================================*/
}
}
}
}
private void ExportImage(IBuffer data, string outputPath)
{
FileStream outputStream;
try
{ outputStream = new FileStream(outputPath, FileMode.CreateNew); }
catch (Exception e)
{ throw new Exception(outputPath + " file couldn't be created.", e); }
try
{
BinaryWriter writer = new BinaryWriter(outputStream);
//ImageConverter ic = new ImageConverter();
//Image img = (Image)ic.ConvertFrom(data);
writer.Write(data.ToByteArray());
writer.Close();
outputStream.Close();
}
catch (Exception e)
{ throw new Exception(outputPath + " file writing has failed.", e); }
Console.WriteLine("Output: " + outputPath);
}
private void txtOutputPath_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnBrowseOutput_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
txtOutputPath.Text = folderBrowserDialog1.SelectedPath;
}
private void btnsave_Click(object sender, EventArgs e)
{
if(txtOutput.Text=="")
{
MessageBox.Show("text box is empty");
}
else
{
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter yaz = new StreamWriter(saveFileDialog1.FileName.ToString());
string yasoutput = txtOutput.Text;
yaz.Write(yasoutput);
}
}
}
private void btncancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnclear_Click(object sender, EventArgs e)
{
txtFileName.Text = "";
txtOutput.Text = "";
txtOutputPath.Text = "";
}
}
}
You would need to invert the image buffer i.e copy the image buffer that you receive to a new buffer starting from the last byte of the image buffer to the first byte of the image buffer. This should take care of the inverted image. The for each pixel data, assuming 24-bit RGB values, swap the R and B values such that RGB becomes BGR. This should get rid of the 'negative' effect and save this new buffer.
Pass your bitmap image to the below function...
private byte[] BmpToBytes_Unsafe (Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0,0,IMAGE_WIDTH,IMAGE_HEIGHT),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
int lineSize = bData.Width * 3;
int byteCount = lineSize * bData.Height;
byte[] bmpBytes = new byte[byteCount];
byte[] tempLine = new byte[lineSize];
int bmpIndex = 0;
IntPtr scan = new IntPtr(bData.Scan0.ToInt32() + (lineSize * (bData.Height-1)));
for (int i = 0; i < bData.Height; i++)
{
Marshal.Copy(scan, tempLine, 0, lineSize);
scan = new IntPtr(scan.ToInt32()-bData.Stride);
tempLine.CopyTo(bmpBytes, bmpIndex);
bmpIndex += lineSize;
}
bmp.UnlockBits(bData);
return bmpBytes;
}
Happy coding...:)

Categories

Resources