I can't place an image on a docx document programmatically generated - c#

I am building a desktop application that generates a .docx document with data that I pull from an SQLite database. I am using Xceed's DocX Nuget package to build it, and I can write text without any complication.
However, my application needs to place an image ON THE HEADER. I pull the image with ease from the database, but I fail when I try to send it to the .docx file.
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Documento Word (*.docx)|*.docx",
FileName = "Documento " + obj_eObra.ProcesoDeSeleccion + ".docx",
DefaultExt = ".docx"
};
if (saveFileDialog.ShowDialog() == true)
{
DocX document = DocX.Create(saveFileDialog.FileName);
Stream Logo = new MemoryStream(obj_eEmpresa.Logo);
Xceed.Document.NET.Image image = document.AddImage(Logo);
document.AddHeaders();
document.AddFooters();
// Force the first page to have a different Header and Footer.
document.DifferentFirstPage = true;
// Force odd & even pages to have different Headers and Footers.
document.DifferentOddAndEvenPages = true;
// Insert a Paragraph into the first Header.
document.Headers.First.Images.Add(image);
// Insert a Paragraph into this document.
var p = document.InsertParagraph();
// Append some text and add formatting.
p.Append("This is a simple formatted red bold paragraph")
.Font(new Font("Arial"))
.FontSize(25)
.Color(System.Drawing.Color.Red)
.Bold()
.Append(" containing a blue italic text.").Font(new Font("Times New Roman")).Color(System.Drawing.Color.Blue).Italic()
.SpacingAfter(40);
document.Save();
}
I expect to see a file that has an image in the header and the following paragraph in the body of the document:
"This is a simple formatted red bold paragraph containing a blue italic text.
But my file only has text, no image.

I did it! Here's the solution
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Documento Word (*.docx)|*.docx",
FileName = "Documento " + obj_eObra.ProcesoDeSeleccion + ".docx",
DefaultExt = ".docx"
};
if (saveFileDialog.ShowDialog() == true)
{
DocX document = DocX.Create(saveFileDialog.FileName);
Stream Logo = new MemoryStream(obj_eEmpresa.Logo);
Xceed.Document.NET.Image image = document.AddImage(Logo);
document.AddHeaders();
document.AddFooters();
// Force the first page to have a different Header and Footer.
document.DifferentFirstPage = true;
// Force odd & even pages to have different Headers and Footers.
document.DifferentOddAndEvenPages = true;
// Insert a Paragraph & image into the first Header.
var picture = image.CreatePicture();
var p = document.Headers.First.InsertParagraph("");
p.AppendPicture(picture);
p.SpacingAfter(30);
// Insert a Paragraph into this document.
Paragraph CiudadYFecha = document.InsertParagraph();
// Append some text and add formatting.
CiudadYFecha.Append("\n\n\n" + obj_eObra.Ciudad + ", " + obj_eObra.FechaActual + ".\n\nSeñores: " + "\n" + obj_eObra.Cliente + "\n\nAtt.: Comité de Selección " + "\nRef.: " + "<Insertar adjudicacion> " + "N° " + obj_eObra.ProcesoDeSeleccion)
.Font(new Font("Times New Roman"))
.FontSize(12)
.SpacingAfter(40);
Paragraph Cuerpo = document.InsertParagraph("De nuestra consideración: \n\n" + "Es grato dirigirnos a ustedes en atención al proceso de selección de la referencia, para alcanzarles nuestra oferta técnico – económica.\n\n" + "Sin otro particular, nos suscribimos de ustedes,\n\n" + "Atentamente,\n");
Cuerpo.Font(new Font("Times New Roman"))
.FontSize(12)
.SpacingAfter(40);
document.Save();
}

Related

How to insert a cover page followed by a page break into an existing document?

The task I have is to insert the content of a cover page word document into a set of existing word documents. The existing documents all sit within a ToBeProcessed folder with the covering page stored in it's own folder. The process I have created is to store the contents of the covering page in a string then iterate through the list of existing files opening each one, selecting the start of the document using a range, inserting the text then adding a page break.
So far, everything works as expected except the fact that the page break is being inserted ahead of the covering page content. Can someone please advise how to achieve this? I've included the full content of my program in case anyone has experience of achieving the same result in a more efficient manner but from my research, the use of range seems to be best practice.
const string COVERING_FOLDER = #"C:\Users\alex.grimsley1\Documents\DocmanLetters\CoveringPage";
const string COMPLETE_FOLDER = #"C:\Users\alex.grimsley1\Documents\DocmanLetters\Complete";
const string LOG_FOLDER = #"C:\Users\alex.grimsley1\Documents\DocmanLetters\Log";
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss"));
StreamWriter logfile = new StreamWriter(LOG_FOLDER + #"\Log_" + DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss") + #".txt");
//Returns an array of strings which contains the list of filenames to be edited
var files = Directory.GetFiles(PROCESSING_FOLDER);
//Creates a new Application wrapper
Application ap = new Application();
//Open the Covering Page document
var cp = ap.Documents.Open(COVERING_FOLDER + "\\CoveringPage.docx");
//Copy the Covering Page contents to a variable for later use
var cpContent = cp.Content.Text;
//Close the Covering Page document
cp.Close(WdSaveOptions.wdDoNotSaveChanges);
//Loop through the file list
foreach(var file in files)
{
if(file.Substring(0, PROCESSING_FOLDER.Length + 1) == PROCESSING_FOLDER + "~")
{
Console.WriteLine("Skipping temporary file: " + file);
} else
{
try
{
object missing = System.Type.Missing;
//Open each file using the Application wrapper
var d = ap.Documents.Open(file);
ap.Visible = true;
var dName = d.Name;
//Select a range at the very start of the Document
var rng = d.Range(0, 0);
d.Unprotect();
d.Protect(WdProtectionType.wdNoProtection);
//Add covering page text to the Document
rng.Text = cpContent;
rng.Collapse(WdCollapseDirection.wdCollapseEnd);
rng.InsertBreak(WdBreakType.wdPageBreak);
//Write the Document name to the Console
Console.WriteLine(d.Name);
//Save the document in place
d.Save();
//Close the document
d.Close(WdSaveOptions.wdDoNotSaveChanges);
//Move the file to the Complete folder
File.Move(file, COMPLETE_FOLDER + "\\" + dName);
//Log the completion of the letter
logfile.WriteLine("Complete " + DateTime.Now.ToString() + " - " + d.Name);
}
catch(Exception e)
{
Console.WriteLine("There was an error: " + e.Message);
//Log the completion of the letter
logfile.WriteLine("Error " + DateTime.Now.ToString() + " - " + e.Message);
}
finally
{
// Close Word application
ap.Quit();
Marshal.ReleaseComObject(ap);
ap = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
Console.WriteLine("Processing complete...");
Console.ReadLine();
}```

Why does WriteLine in C# change my format in Text File?

So I'm writing an app and without any problem I was getting streamwriter to write new lines using the WriteLine. However, when I got to a certain textbox it automatically started indenting. Please see below image and code:
This is under a save button
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = #"C:\DR\Desktop\4-22-18";
sfd.RestoreDirectory = true;
sfd.FileName = "G-12";
sfd.Filter = "txt files(*.txt)|*.txt| Word Files | *.doc";
if (sfd.ShowDialog()==DialogResult.OK)
{
Stream fileStream = sfd.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(lblDate.Text);
sw.WriteLine(lblTime.Text);
sw.WriteLine("\r");
sw.WriteLine("G-12"+"\t"+ lblNotes.Text + " " + txtNotes.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblSG.Text+" "+ nmSG.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblTinWeight.Text + " " + nmTinWeight.Text);
sw.WriteLine(lblKIO3.Text + " "+ nmKIO3Volume.Text);
sw.WriteLine(lblKIO3N.Text + nmKIO3N.Text);
sw.WriteLine(lblTinPercentage.Text + " "+ lblTinPercent.Text);
sw.WriteLine(lblTinGram.Text + lblTinGrams.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblNeutWeight.Text+nmNeutWeight.Text);
sw.WriteLine(lblNeutVolume.Text+nmNaOHVolume.Text);
sw.WriteLine(lblNeutNormality.Text + nmNaOHNormality.Text);
sw.Close();
}
enter image description here
The text box contains a space. Verify this by looking the value of lblTinWeight.Text (or a different textbox, not sure) in the debugger.

How to add multiple fonts to a single line of text with iTextSharp

In plant classification the family-genus-species is normally written in italics with any variety in normal text.
Rosaceae Sorbus aucuparia 'Fastigiata'
I'm trying to achieve this in c# using the iTextSharp library. Could anyone help?
I've made two different font objects. Added each one to two different chunk objects and then added the chunks to a phrase object before finally adding the phrase to a table cell.
Current output is the whole line is in italics.
Rosaceae Sorbus aucuparia 'Fastigiata'
iTextSharp.text.Font fontHeader = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 15f);
iTextSharp.text.Font fontHeaderItalic = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 15f, iTextSharp.text.Font.ITALIC);
Phrase phrase = new Phrase(new Chunk(plant.strFamily + " " + plant.strGenus + " " + plant.strSpecies, fontHeaderItalic));
if(plant.strVariety != null)
phrase.Add(new Chunk(" '" + plant.strVariety + "'", fontHeader));
tableHeader.AddCell(new PdfPCell(phrase) { Border = 0 });

Save text to Exisit file c#

I'am trying to add new text to exist file which i created but when he click save i have always the same save us. Program adding text but i always must create new text.
string text = System.IO.File.ReadAllText(#"D:\test.txt");
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
text = "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(saveFileDialog1.FileName, text);
}
}
You can add your text in string[] or List and after that add in text file.
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
List<string> appendLines = new List<string>()
{
"one string",
"two string"
};
File.AppendAllLines(saveFileDialog.FileName, appendLines);
}
}
Change text = to text +=, and also use WriteAllText in case the file is the same as the one you just read in (otherwise you will read in the file, then append the same data back into the file). Currently you are reading a file into the variable text, the immediately overwriting all of that data with new data.
string text = System.IO.File.ReadAllText(#"D:\test.txt");
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
text += "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(saveFileDialog1.FileName, text);
}
Or, if you really want to use AppendAllText and simply want to append to an existing file, you actually want to leave your text = unchanged and do this instead (no reason to read in the file):
string fileName = #"D:\test.txt";
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string text = "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(fileName, text);
}

label printer incorrectly prints itextsharp documents

the code below generate pdf documents:
using (FileStream fs = new FileStream("st.csv", FileMode.Open))
{
using (StreamReader configFile = new StreamReader(fs, System.Text.Encoding.GetEncoding("windows-1250")))
{
string line = string.Empty;
while ((line = configFile.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
line = line.Replace("\"", "");
string[] varible = line.Split(';');
string number = varible[0];
string stName = varible[1];
string ewidenceNumber = varible[2];
string fileName = "barcodes\\" + Encryption.RandomString(10, true) + ".png";
Generate(line, fileName);
PdfPTable Table = new PdfPTable(2);
Table.WidthPercentage = 100;
Table.SetWidths(new[] { 110f, 190f });
iTextSharp.text.Image barcode = iTextSharp.text.Image.GetInstance(fileName);
barcode.Border = 0;
barcode.ScalePercent(180f);
PdfPCell imageCell = new PdfPCell(barcode);
imageCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(imageCell);
PdfPCell descriptionCell = new PdfPCell(new Paragraph(
"Enterprise 1 \n\n" +
number + "\n\n" +
"Number1: " + stName + "\n\n" +
"Number2: " + ewidenceNumber, _standardFont));
descriptionCell.HorizontalAlignment = Element.ALIGN_CENTER;
descriptionCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(descriptionCell);
Table.KeepTogether = true;
Table.SpacingAfter = 10f;
doc.Add(Table);
}
}
}
}
and here is the problem: vertical and horizontal view in adobe acrobat displays correctly, but when I need to print labels with this information CITIZEN label printer always prints it in horizontal view. I can't adapt this data to print in correct orientation. Anyone has solution for this problem? Maybe I incorrectly rotate cells in table?
I would suggest you drop PDF and instead write to it's native format: http://www.citizen-europe.com/support/progman.htm
PDF printing support is supplied by the driver. If the driver doesn't know how to interpret the specific PDF commands then it's not going to work. Usually label printers don't provide very good driver support for anything but writing to their native format or emulating ZPL (zebra) and Datamax.

Categories

Resources