/// <summary> /// Converts a Word document to PDF /// </summary> /// <param name="inputFile">The Word input file</param> /// <param name="outputFile">The PDF output file</param> /// <returns></returns> internal static void Convert(string inputFile, string outputFile) { DeleteAutoRecoveryFiles(); WordInterop.ApplicationClass word = null; WordInterop.DocumentClass document = null; try { word = new WordInterop.ApplicationClass { ScreenUpdating = false, DisplayAlerts = WordInterop.WdAlertLevel.wdAlertsNone, DisplayDocumentInformationPanel = false, DisplayRecentFiles = false, DisplayScrollBars = false, AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable }; word.Options.UpdateLinksAtOpen = false; word.Options.ConfirmConversions = false; word.Options.SaveInterval = 0; word.Options.SaveNormalPrompt = false; word.Options.SavePropertiesPrompt = false; word.Options.AllowReadingMode = false; word.Options.WarnBeforeSavingPrintingSendingMarkup = false; word.Options.UpdateFieldsAtPrint = false; word.Options.UpdateLinksAtOpen = false; word.Options.UpdateLinksAtPrint = false; document = (WordInterop.DocumentClass)Open(word, inputFile, false); // Do not remove this line!! // This is yet another solution to a weird Office problem. Sometimes there // are Word documents with images in it that take some time to load. When // we remove the line below the ExportAsFixedFormat method will be called // before the images are loaded thus resulting in an unendless loop somewhere // in this method. // ReSharper disable once UnusedVariable var count = document.ComputeStatistics(WordInterop.WdStatistic.wdStatisticPages); word.DisplayAutoCompleteTips = false; word.DisplayScreenTips = false; word.DisplayStatusBar = false; document.ExportAsFixedFormat(outputFile, WordInterop.WdExportFormat.wdExportFormatPDF); } finally { if (document != null) { document.Saved = true; document.Close(false); Marshal.ReleaseComObject(document); } if (word != null) { word.Quit(false); Marshal.ReleaseComObject(word); } } }
/// <summary> /// WordファイルをPDFとして保存します。 /// </summary> /// <param name="wordFilePathName">Wordファイルのパス付きファイル名。</param> /// <param name="saveAsPathName">保存するPDFのパス付きファイル名。</param> /// <remarks> /// <para> /// Word 2013がインストールされている必要があります。 /// </para> /// </remarks> public static void SaveAsPdf(string wordFilePathName, string saveAsPathName) { // Word 2013がインストールされている必要があります。 MSWord.ApplicationClass application = null; MSWord.Documents documents = null; MSWord.DocumentClass document = null; // refキーワードと共に渡すので、変数である必要がある。 object missing = System.Type.Missing; try { application = new MSWord.ApplicationClass(); /* * application.Documents.Open(...は、Documentsオブジェクトの解放処理ができないので不可。 * 必ず変数経由でComRelease.FinalReleaseComObjectsを呼び出すこと。 */ documents = application.Documents; object filePathName = wordFilePathName; object ReadOnly = true; object Visible = false; document = (MSWord.DocumentClass)documents.Open( ref filePathName, ref missing, ref ReadOnly, ref missing, ref missing , ref missing, ref missing, ref missing, ref missing, ref missing , ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing); // ExportAsFixedFormatのパラメータは以下を参照 // http://msdn.microsoft.com/ja-jp/library/microsoft.office.tools.word.document.exportasfixedformat.aspx // http://msdn.microsoft.com/en-us/library/bb412305.aspx document.ExportAsFixedFormat( saveAsPathName, MSWord.WdExportFormat.wdExportFormatPDF, false, MSWord.WdExportOptimizeFor.wdExportOptimizeForPrint, MSWord.WdExportRange.wdExportAllDocument, 0, 0, MSWord.WdExportItem.wdExportDocumentWithMarkup, true, true, MSWord.WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref missing); } finally { if (document != null) { try { document.Close(ref missing, ref missing, ref missing); } catch { } } if (application != null) { try { application.Quit(ref missing, ref missing, ref missing); } catch { } } Com.ComRelease.FinalReleaseComObjects(document, documents, application); } }
public static void ReadFromFile(Object filename) { // String[] Names = new String[34] { "Александров А.А.", "Амосов А.А.", "Амосова О.А.", "Ахметшин А.А", "Бредихин Р.Н.", "Булычева О.Н.", " Вестфальский А.Е.", "Горелов В.А.", "Горицкий Ю.А.", "Григорьев В.П.", "Дубинский Ю.А.", "Дубовицкая Н.В.", "Жилейкин Я.М.", "Заславский А.А.", "Злотник А.А.", "Зубков П.В.", "Зубов В.С.", "Игнатьева Н.У.", "Ишмухаметов А.З.", "Казенкин К.О.", "Кирсанов М.Н.", "Князев А.В.", "Крупин Г.В.", "Кубышин С.Ю.", "Ляшенко Л.И.", "Мамонтов А.И.", "Макаров П.В.", "Мещанинов Д.Г.", "Набебин А.А.", "Перескоков А.В.", "Титов Д.А.", "Фролов А.Б.", "Черепова М.Ф.", "Шевченко И.В." }; Form1.form.SetProc(0); Word.Application app = new Word.ApplicationClass(); Word.Document doc = new Word.DocumentClass(); Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Type.Missing; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; doc = app.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); if (doc.Tables.Count == 0) { //Err. TODOk } else { DataMass.saveAndClear(".doc"); for (int i = 1; i <= doc.Tables.Count; i++) { Form1.form.SetProc(i * 5 / doc.Tables.Count); formatTimeTable buf = new formatTimeTable("", 6); Word.Table t = doc.Tables[i]; for (int k = 2; k <= t.Columns.Count; k++) { for (int j = 2; j <= t.Rows.Count; j++) { string str = t.Cell(j, k).Range.Text; Lesson A = new Lesson(0); A.italy = (t.Cell(j, k).Range.Italic != -1); A.fromString(str); if (j <= 6 && k < 7) { buf.lesson[k - 2, j - 2] = A; } //Записано. if (t.Rows.Count < 8) { A = new Lesson(0); } A.fromString(""); buf.lesson[k - 2, j - 1] = A; } } Data.teacher.Add(buf); } } //считывания имен int StrI = 0; string txt; for (int i = 1; i <= doc.Paragraphs.Count; i++) { Form1.form.SetProc(5 + i * 95 / doc.Paragraphs.Count); txt = doc.Paragraphs[i].Range.Text; txt = FindName(txt); if (txt != "") { Data.teacher[StrI++].name = txt; i += 39; } // if (Data.teacher.Count == StrI) break; } for (int i = 0; i < Data.teacher.Count; i++) { if (Data.teacher[i].name == "") { Data.teacher.RemoveAt(i); i--; } } Object saveChanges = Word.WdSaveOptions.wdSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; app.Quit(ref saveChanges, ref originalFormat, ref routeDocument); return; }
public void Izradi_er1() { Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document document = new Microsoft.Office.Interop.Word.DocumentClass(); try { decimal num2 = 0; decimal num9 = 0; decimal num10 = 0; decimal num5 = 0; decimal num6 = 0; decimal num7 = 0; decimal num4 = 0; decimal num8 = 0; IEnumerator enumerator = null; application.Visible = false; object temp = System.Reflection.Missing.Value; object confirmConversions = true; object readOnly = true; object path = System.Windows.Forms.Application.StartupPath + @"\App_Data\Potvrda_o_placi.doc"; document = application.Documents.Open(ref path, ref confirmConversions, ref readOnly, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp); document.ActiveWindow.View.ReadingLayout = false; KORISNIKDataSet dataSet = new KORISNIKDataSet(); new KORISNIKDataAdapter().Fill(dataSet); document.Fields[1].Result.Text = Conversions.ToString(dataSet.KORISNIK.Rows[0]["KORISNIK1NAZIV"]); int startIndex = 0; do { // Veličina ovog polja u bazi je 11 mjesta, ali se očito kod korisnika dešava da imaju po 10 mjesta if (dataSet.KORISNIK.Rows[0]["KORISNIK1HZZO"].ToString().Length > startIndex) { document.Fields[2 + startIndex].Result.Text = dataSet.KORISNIK.Rows[0]["KORISNIK1HZZO"].ToString().Substring(startIndex, 1); } startIndex++; }while (startIndex <= 10); document.Fields[13].Result.Text = Conversions.ToString(this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["PREZIME"]); document.Fields[14].Result.Text = Conversions.ToString(this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["IME"]); startIndex = 0; do { document.Fields[15 + startIndex].Result.Text = this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["jmbg"].ToString().Substring(startIndex, 1); startIndex++; }while (startIndex <= 3); document.Fields[0x13].Result.Text = "1"; try { document.Fields[20].Result.Text = this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["jmbg"].ToString().Substring(4, 1); document.Fields[0x15].Result.Text = this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["jmbg"].ToString().Substring(5, 1); document.Fields[0x16].Result.Text = this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["jmbg"].ToString().Substring(6, 1); } catch (Exception) { } startIndex = 0; do { document.Fields[0x17 + startIndex].Result.Text = this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["OIB"].ToString().Substring(startIndex, 1); startIndex++; }while (startIndex <= 10); string str = DB.N2T(RuntimeHelpers.GetObjectValue(this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["BROJZDRAVSTVENOG"]), ""); if (str.Trim() != "") { startIndex = 0; do { if (str.Length > startIndex) { document.Fields[0x22 + startIndex].Result.Text = str.Substring(startIndex, 1); } startIndex++; }while (startIndex <= 10); } startIndex = 0; do { document.Fields[34 + startIndex].Result.Text = this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows[0]["jmbg"].ToString().Substring(startIndex, 1); startIndex++; }while (startIndex <= 12); string str3 = Conversions.ToString(this.UltraCombo1.Value); string str2 = Conversions.ToString(this.UltraCombo2.Value); DateTime time = DateAndTime.DateSerial(Conversions.ToInteger(str3.Substring(0, 4)), Conversions.ToInteger(str3.Substring(5, 2)), Conversions.ToInteger("1")); DateTime time2 = DateAndTime.DateSerial(Conversions.ToInteger(str2.Substring(0, 4)), Conversions.ToInteger(str2.Substring(5, 2)), Conversions.ToInteger("1")); time = time.AddMonths(1); time2 = time2.AddMonths(2).AddDays(-1.0); str3 = time.ToString("ddMMyyyy", CultureInfo.InvariantCulture); str2 = time2.ToString("ddMMyyyy", CultureInfo.InvariantCulture); startIndex = 0; do { document.Fields[47 + startIndex].Result.Text = str3.Substring(startIndex, 1); startIndex++; }while (startIndex <= 7); startIndex = 0; do { document.Fields[55 + startIndex].Result.Text = str2.Substring(startIndex, 1); startIndex++; }while (startIndex <= 7); int num = 63; try { enumerator = this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows.GetEnumerator(); while (enumerator.MoveNext()) { DataRow current = (DataRow)enumerator.Current; document.Fields[num].Result.Text = Conversions.ToString(Operators.AddObject(Operators.AddObject(current["mjesecobracuna"], "/"), current["godinaobracuna"])); document.Fields[num + 1].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["ukupnobruto"])); document.Fields[num + 2].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["netoplaca"])); document.Fields[num + 3].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["kolona4"])); document.Fields[num + 4].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["kolona5"])); document.Fields[num + 5].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["kolona6"])); document.Fields[num + 6].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["satiukupno"])); document.Fields[num + 7].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["kolona8"])); document.Fields[num + 8].Result.Text = string.Format("{0:#,##0.00}", RuntimeHelpers.GetObjectValue(current["fondmjeseca"])); num += 9; num2 = Conversions.ToDecimal(Operators.AddObject(num2, current["ukupnobruto"])); num9 = Conversions.ToDecimal(Operators.AddObject(num9, current["netoplaca"])); num5 = Conversions.ToDecimal(Operators.AddObject(num5, current["kolona4"])); num6 = Conversions.ToDecimal(Operators.AddObject(num6, current["kolona5"])); num7 = Conversions.ToDecimal(Operators.AddObject(num7, current["kolona6"])); num10 = Conversions.ToDecimal(Operators.AddObject(num10, current["satiukupno"])); num8 = Conversions.ToDecimal(Operators.AddObject(num8, current["kolona8"])); num4 = Conversions.ToDecimal(Operators.AddObject(num4, current["fondmjeseca"])); if (((this.S_OD_BOLOVANJE_FONDDataSet1.S_OD_BOLOVANJE_FOND.Rows.Count * 9) + 63) == num) { document.Fields[117].Result.Text = string.Format("{0:#,##0.00}", num2); document.Fields[118].Result.Text = string.Format("{0:#,##0.00}", num9); document.Fields[119].Result.Text = string.Format("{0:#,##0.00}", num5); document.Fields[120].Result.Text = string.Format("{0:#,##0.00}", num6); document.Fields[121].Result.Text = string.Format("{0:#,##0.00}", num7); document.Fields[122].Result.Text = string.Format("{0:#,##0.00}", num10); document.Fields[123].Result.Text = string.Format("{0:#,##0.00}", num8); document.Fields[124].Result.Text = string.Format("{0:#,##0.00}", num4); } } } finally { if (enumerator is IDisposable) { (enumerator as IDisposable).Dispose(); } } if (decimal.Compare(num10, decimal.Zero) > 0) { document.Fields[125].Result.Text = string.Format("{0:#,##0.00}", DB.RoundUpDecimale(decimal.Divide(num2, num10), 2)); document.Fields[126].Result.Text = string.Format("{0:#,##0.0000}", decimal.Divide(num9, num10), 2); } else { document.Fields[125].Result.Text = string.Format("{0:#,##0.00}", 0); document.Fields[126].Result.Text = string.Format("{0:#,##0.00}", 0); } document.Fields[127].Result.Text = Conversions.ToString(dataSet.KORISNIK.Rows[0]["korisnik1mjesto"]); document.Fields[128].Result.Text = Conversions.ToString(DateAndTime.Year(DateAndTime.Today)).Substring(2, 2); FolderBrowserDialog dialog = new FolderBrowserDialog(); SaveFileDialog dialog2 = new SaveFileDialog { InitialDirectory = @"C:\Desktop", Filter = "Word datoteke (*.doc)|*.doc|All files (*.*)|*.*", FileName = "Bolovanje_HZZO_Obrazac", RestoreDirectory = true }; dialog2.ShowDialog(); SaveFileDialog dialog3 = dialog2; object fileName = dialog3.FileName; document.SaveAs(ref fileName, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp, ref temp); dialog3.FileName = Conversions.ToString(fileName); } catch (Exception exception) { MessageBox.Show("Greška u generiranju izvještaja: 'Prosjek bolovanje/HZZO'!" + Environment.NewLine + "Molimo provjerite valjanost/postojanost podataka koji su potrebni za generiranje izvještaja.", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error); new Mipsed7.Emailing.SendException(exception); } finally { //document.Close(false, Missing.Value, Missing.Value); ((_Document)document).Close(false, Missing.Value, Missing.Value); //application.Quit(false, Missing.Value, Missing.Value); ((_Application)application).Quit(false, Missing.Value, Missing.Value); // za svaki slučaj if (document != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(document); } if (application != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(application); } // isprazni varijable document = null; application = null; // force-amo GarbageCollector (za svaki slučaj) GC.Collect(); this.Cursor = Cursors.Default; } }
public static void CreateWordDoc(string name) { #region inicialization Form1.form.SetProc(0); int namesLen = Data.teacher.Count; const int pairLen = 4;//Сколько пар в день отображать string[] daysNames = { "Понедельник", "Вторник", "Среда", "Четверг", "Пятница" }; string[] times = { "9.30-10.30", "11.10–12.45", "13.45–15.20", "15.35–17.10", "17.25–19.00??" }; object nr = 1; object nc = pairLen; object start = 0; object end = 0; const int dayWidth = 120; //ширина одного дня const int namesWidth = 95; //ширина имен. Word.Application app = new Word.ApplicationClass(); Word.Document doc = new Word.DocumentClass(); Object template = Type.Missing; Object newTemplate = Type.Missing; Object documentType = Type.Missing; Object visible = Type.Missing; app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible); Object DefaultTableBehavior = Type.Missing; Object AutoFitBehavior = Type.Missing; //Формирование страницы doc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; //Создание таблицы Word.Range cellRange; Word.Range tableLocation = doc.Range(ref start, ref end); doc.Tables.Add(tableLocation, namesLen + 2, 7, ref DefaultTableBehavior, ref AutoFitBehavior); Word.Table table = doc.Tables[1]; table.Borders.Enable = 1; table.Rows.SetHeight(14f, Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly); //Формирование Шрифтов Word.Font TextFont = new Word.Font(); TextFont.Size = 8; TextFont.Bold = 0; table.Cell(1, 1).Width = namesWidth; cellRange = table.Cell(1, 1).Range; cellRange.Font = TextFont; #endregion formatTable(ref table, ref TextFont, pairLen, dayWidth, namesWidth, namesLen, cellRange); setBorders(ref table, pairLen); setDateToTable(ref doc, ref TextFont, pairLen, dayWidth, namesWidth, namesLen); #region save Object fileName = name;//@"C:\Test\Форматированная_Таблица.doc"; Object fileFormat = Type.Missing; Object lockComments = Type.Missing; Object password = Type.Missing; Object addToRecentFiles = Type.Missing; Object writePassword = Type.Missing; Object readOnlyRecommended = Type.Missing; Object embedTrueTypeFonts = Type.Missing; Object saveNativePictureFormat = Type.Missing; Object saveFormsData = Type.Missing; Object saveAsAOCELetter = Type.Missing; Object encoding = Type.Missing; Object insertLineBreaks = Type.Missing; Object allowSubstitutions = Type.Missing; Object lineEnding = Type.Missing; Object addBiDiMarks = Type.Missing; doc.SaveAs(ref fileName, ref fileFormat, ref lockComments, ref password, ref addToRecentFiles, ref writePassword, ref readOnlyRecommended, ref embedTrueTypeFonts, ref saveNativePictureFormat, ref saveFormsData, ref saveAsAOCELetter, ref encoding, ref insertLineBreaks, ref allowSubstitutions, ref lineEnding, ref addBiDiMarks); Object saveChanges = Word.WdSaveOptions.wdSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; app.Quit(ref saveChanges, ref originalFormat, ref routeDocument); #endregion }