I am working on an Salary Project and what i want to do is
when an user see their Salary slip and click on Downloads then the complete form data is converted into PDf file and stored on an predifined location..
plz suggest the code to meet my requirements..
I had faced this problem before, and the best I found to solve it was to user Microsoft Word Interops. You can put whatever you want in a word document and then save it as PDF, fortunately Microsoft word allows you to export the document to PDF.
The simplest way to do this would be to save your data as just plain text, but don't forget to well format them, and then run this method to convert the plain text to PDF.
public PDFWriter(String Path, String FileName) {
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
try
{
word.Visible = false;
word.Documents.Open(Path);
word.ActiveDocument.SaveAs2(FileName + ".pdf", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
this.Path = FileName + ".pdf";
}
catch (Exception e)
{
word.Quit();
throw new Exception(e.Message);
}
finally
{
word.Quit();
}
}
Download pdfSharp.dll pdfSharp
and add it as reference.
Capture your form as image and then
private void ImageToPdf()
{
PdfSharp.Pdf.PdfDocument doc = new PdfSharp.Pdf.PdfDocument();
PdfSharp.Pdf.PdfPage oPage = new PdfSharp.Pdf.PdfPage();
String destinaton = "your destination";
doc.Pages.Add(oPage);
XGraphics xgr;
XImage img;
img = XImage.FromGdiPlusImage(form image);
xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(oPage);
xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
}
valter
Related
I'm creating one winforms desktop application in c# that load .docx file. I want to load .docx file into RichTextBox. But when I'm trying to load .docx file, the format of that file is not getting correct. is there any other control or method to load and save .docx file with correct document format?
Use this to read the file text and add the returned string to the Richtextbox.
private string GetWordFileText(string filepath)
{
Microsoft.Office.Interop.Word.ApplicationClass WordApp = null;
Microsoft.Office.Interop.Word.Document doc = null;
try
{
WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
doc = WordApp.Documents.Open(filepath, Visible: false);
string toReturn = doc.Content.Text;
return toReturn;
}
catch (Exception e)
{ throw e; }
finally
{
doc.Close();
WordApp.Quit();
}
}
After this comes the document styling. I don't have a code snippet handy for this but it would technically work as follows:
var formatting = Dictionary<string, Style>();
foreach(Paragraph para in doc.Paragraphs)
{
formatting.Add(para.Range.Text, (Style) para.getStyle());
}
Then inside the RichTextbox control you should figure out a method to apply styling
foreach(var fItem in formatting)
{
ApplyStyle(richTextBox, fItem.Key, fItem.Value);
}
void ApplyStyle(RichTextBox tb, string toFormat, Style style)
{
tb.SelectionFont = new Font(style.Font.Name, style.Font.Size);
tb.SelectedText = toFormat;
}
Finally, I got an answer. For load, Edit, Display - You can use RichEditControl of DexExpress tool, It comes up with all features of Word and also you can load RTF, .doc, .docx files in this control and edit it.
so I am looking for a way to convert Excel, PowerPoint, PDF, and Word to Images. I was wondering if anyone has experience with the Aspose suite and knows if all of this can be done with the Aspose.PDF suite, or would I need to get Aspose.slides, and Aspose.word as well?
You will need Aspose.Slides, Aspose.Words, Aspose.Cells and Aspose.Pdf or you can use Web Api
Conversion from office document to image could be done without using any third party component. Below code will convert specific range from an Excel worksheet to Image, for example.
IMPORTANT: Don't forget to mark the method with [STAThread] attribute.
Usings:
using xls = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Windows.Forms;
Conversion Code:
[STAThread]
static void Main(string[] args)
{
string fileNameToProcess = #"D:\Book2.xlsx";
//Start Excel and create a new document.
xls.Application oExcel = new xls.Application();
xls.Workbook wb = null;
try
{
wb = oExcel.Workbooks.Open(
fileNameToProcess.ToString(), false, false, Type.Missing, "", "", true, xls.XlPlatform.xlWindows, "", false, false, 0, false, true, 0);
//wb.RefreshAll();
xls.Sheets sheets = wb.Worksheets as xls.Sheets;
xls.Worksheet sheet = sheets[1];
//Following is used to find range with data
string startRange = "A1";
string endRange = "P25";
xls.Range range = sheet.get_Range(startRange, endRange);
range.CopyPicture(xls.XlPictureAppearance.xlScreen, xls.XlCopyPictureFormat.xlBitmap);
System.Drawing.Image imgRange = GetImageFromClipboard();
imgRange.Save(#"d:\ExcelSheetImage.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
wb.Save();
Console.Write("Specified range converted to image successfully. Press Enter to continue.");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//throw;
}
finally
{
wb.Close();
oExcel.Quit();
oExcel = null;
}
Console.ReadLine();
}
public static System.Drawing.Image GetImageFromClipboard()
{
System.Drawing.Image returnImage = null;
// This doesn't work
//if (Clipboard.ContainsImage())
//{
// returnImage = Clipboard.GetImage();
//}
//return returnImage;
// This works
System.Windows.Forms.IDataObject d = Clipboard.GetDataObject();
if (d.GetDataPresent(DataFormats.Bitmap))
{
returnImage = Clipboard.GetImage();
}
return returnImage;
}
My name is Nayyer and I am working as developer evangelist at Aspose.
Aspose.Words is provides the feature to create/manipulate MS word
documents and it also offers the feature to convert word documents
into Image format. You may check following link for more details on
convert MS Word document to Image (simply select Jpeg, Png, Bmp
from SaveFormat enumeration).
Similarly you can use Aspose.Cells to convert Excel worksheets into Image format. Converting worksheet into Image
Aspose.Slides can be used to convert PowerPoint
presentations to Image format. Create Thumbnail image of slide.
Aspose.Pdf supports the feature to transform PDF pages into Image
format. For further details, please visit Convert all PDF pages to
JPEG format.
I know it's 2019, but if anyone is still wondering, you can do this using Aspose.Words.
The following values (and more) in the SaveFormat enum are available:
Tiff = 100,
//
// Summary:
// Renders a page of the document and saves it as a PNG file.
Png = 101,
//
// Summary:
// Renders a page of the document and saves it as a BMP file.
Bmp = 102,
//
// Summary:
// Renders a page of the document and saves it as a JPEG file.
Jpeg = 104,
//
// Summary:
// Renders a page of the document and saves it as a GIF file.
Gif = 105
You would use them like so:
var fileContents = asposeDocument.GenerateDocument(Aspose.Words.SaveFormat.Png);
I would like to fill in form fields in a premade PDF doc, but I'm receiving a Null Refrence error with AcroForm when running.
string fileN4 = TextBox1.Text + " LOG.pdf";
File.Copy(Path.Combine(textBox4.Text + "\\", fileN4),
Path.Combine(Directory.GetCurrentDirectory(), fileN4), true);
// Open the file
PdfDocument document = PdfReader.Open(fileN4, PdfDocumentOpenMode.Modify);
PdfTextField currentField = (PdfTextField)(document.AcroForm.Fields["<CASENUM>"]);
//const
string caseName = TextBox1.Text;
PdfString caseNamePdfStr = new PdfString(caseName);
//set the value of this field
currentField.Value = caseNamePdfStr;
// Save the document...
document.Save(fileN4);
So PdfTextField currentField = (PdfTextField)(document.AcroForm.Fields["<CASENUM>"]); is where the error happens. It seams that AcroForm is not even recognizing the fields.
Another option would be a find and replace text in a PDF (without using itextsharp as cannot use due to licensing).
Any help would be awesome!
You also need this if you are attempting to populate PDF form fields, you also need to set the NeedsAppearances element to true. Otherwise the PDF will "hide" the values on the form. Here is the VB code.
If objPdfSharpDocument.AcroForm.Elements.ContainsKey("/NeedAppearances") = False Then
objPdfSharpDocument.AcroForm.Elements.Add("/NeedAppearances", New PdfSharp.Pdf.PdfBoolean(True))
Else
objPdfSharpDocument.AcroForm.Elements("/NeedAppearances") = New PdfSharp.Pdf.PdfBoolean(True)
End If
I've been working on this today and I've managed to create a working solution. I've pasted my working code below. The only real differences I can see between my code and the OP's is the following:
I included Marc Ferree's code to set NeedAppearances (+1 and Many thanks!!)
I set the Text property of the field using a String variable, and not the Value property using a PdfString.
Hopefully this will be of use to somebody trying to do the same.
string templateDocPath = Server.MapPath("~/Documents/MyTemplate.pdf");
PdfDocument myTemplate = PdfReader.Open(templateDocPath, PdfDocumentOpenMode.Modify);
PdfAcroForm form = myTemplate.AcroForm;
if (form.Elements.ContainsKey("/NeedAppearances"))
{
form.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true);
}
else
{
form.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true));
}
PdfTextField testField = (PdfTextField)(form.Fields["TestField"]);
testField.Text = "012345";
myTemplate.Save(Server.MapPath("~/Documents/Amended.pdf")); // Save to new file.
I got stuck with this same problem earlier today. However, I think the source code has ?updated, so if you try the method above you are going to get a NullExceptionError. Instead, for TextField you need to generate a PdfString and use testfield.Value instead of .text. Here's an example.
static PdfAccess()
{
Pdf.PdfDocument doc = Pdf.IO.PdfReader.Open(#"C:\...\ Contract.pdf", Pdf.IO.PdfDocumentOpenMode.Modify);
Pdf.AcroForms.PdfAcroForm form = doc.AcroForm;
if (form.Elements.ContainsKey("/NeedAppearances"))
{
form.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true);
}
else
{
form.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true));
}
var name = (Pdf.AcroForms.PdfTextField)(form.Fields["Email"]);
name.Value = new Pdf.PdfString("ramiboy");
doc.Save(#"C:\...\ Contract.pdf");
doc.Close();
I have just experienced something similar to this. The first pdf file I opened did not contain acroform data and resulted in a null exception as described above. The issue is not with the opening of the pdf but the reference to the Acroform member variable having a value of null. You can test your pdf using the following code example:
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
PdfDocument _document = null;
try
{
_document = PdfReader.Open(ofd.FileName, PdfDocumentOpenMode.Modify);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"FATAL");
//do any cleanup and return
return;
}
if (_document != null)
{
if (_document.AcroForm != null)
{
MessageBox.Show("Acroform is object","SUCCEEDED");
//pass acroform to some function for processing
_document.Save(#"C:\temp\newcopy.pdf");
}
else
{
MessageBox.Show("Acroform is null","FAILED");
}
}
else
{
MessageBox.Show("Uknown error opening document","FAILED");
}
}
ADENDUM
I also noticed the key in this line of code should not have angle brackets
document.AcroForm.Fields["<CASENUM>"]
Change it to
document.AcroForm.Fields["CASENUM"]
The solution to overcome the NullReferenceException is to open your pre-made
PDF with Adobe Acrobat and give your form fields a default value, by changing their property-type to be something other than null.
Have you tried putting the current directory in when you try to open it?
Change
PdfDocument document = PdfReader.Open(fileN4, PdfDocumentOpenMode.Modify);
to
PdfDocument document = PdfReader.Open(Path.Combine(Directory.GetCurrentDirectory(), fileN4), PdfDocumentOpenMode.Modify);
I'm pretty sure that PdfReader will need a full file path, although I only use ASPOSE for pdf creation.
I have the following code to convert word document to pdf using CutePdf Writer
PrintDialog pDia = new PrintDialog();
PrinterSettings ps = new PrinterSettings();
pDia.Document = printDocumentMessageBoxTest;
pDia.Document.DocumentName = "C:\\FinalGap.doc";
ps.PrinterName = "CutePDF Writer";
ps.PrintToFile = true;
ps.PrintFileName = "C:\\" + Path.GetFileNameWithoutExtension(pDia.Document.DocumentName) + ".pdf";
// take printer settings from the dialog and set into the PrintDocument object
pDia.Document.OriginAtMargins = true;
ps.DefaultPageSettings.Margins.Left = 2;
//printDocumentMessageBoxTest.PrinterSettings = ps;
// start the printing process, catch exceptions
try
{
printDocumentMessageBoxTest.Print();
}
catch (Exception exc)
{
MessageBox.Show("Printing error!\n" + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
When I run the application, it is printing the word document bu the output file is not generated.
Can anyone tell me how to convert word document to pdf using CUTEPDF programatically and waht's wrong with the above code?
CutePdf Writer does not support automation. You can't use it the manner you are trying to use it. You can purchase Custom Pdf Writer from them, then you code will be something like this:
string regKey = #"HKEY_CURRENT_USER\Software\Custom PDF Printer";
Registry.SetValue(regKey, "OutputFile", #"C:\Sample.pdf", RegistryValueKind.String);
Registry.SetValue(regKey, "BypassSaveAs", #"1", RegistryValueKind.String);
Application wordApp = new Word.Application();
Document wordDoc = wordApp.Documents.Open(#"C:\test.doc");
wordApp.ActivePrinter = "Custom PDF Printer";
wordApp.PrintOut();
wordDoc.Close();
Registry.SetValue(regKey, "BypassSaveAs", #"0", RegistryValueKind.String);
Also see:
automation of Doc to PDF in c#
DOC to PDF library (not necessarily free)
convert doc to pdf in c#
Convert single doc file to pdf
C# free Doc 2 PDF solution
Convert .doc and .txt format file into pdf file for for .aspnet?
I personally used ABCPdf for a project and I liked it, however my goal was convert not from doc but from html to pdf and the component were not free.
I am converting a .txt to .pdf in c#. This works fine if the .txt file is not blank. if it is, it threw an error of "The document has no pages".
The pdf gets generated but threw an error of "There was an error opening this document. The file is damaged and could not be repaired" when opening a pdf file.
Code is seen below
public void converttxttoPDF(string sourcePath, string destPath)
{
try
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
string filename = Path.GetFileNameWithoutExtension(sourcePath);
System.IO.StreamReader myFile = new System.IO.StreamReader(sourcePath);
string myString = myFile.ReadToEnd();
myFile.Close();
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destPath + "\\" + filename + ".pdf", FileMode.CreateNew));
document.Open();
document.Add(new iTextSharp.text.Paragraph(myString));
document.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
let me know if any info needed.
thanks
You need to add some content to the pdf. So try this:
myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));
You need to convince iText that there IS something on that page.
Two Methods:
Be explicit. writer.setPageEmpty(false);
Trick it (which is what Darin suggests). writer.getDirectContent().setLiteral(" ");