Einträge mit Tag “visual-basic”

VB .NET: Dateien mit PDFCreator drucken

04. Aug 2008 21:18 (bearbeiten)

Mit den folgenden Funktionen kann man mit Visual Basic .NET unter Verwendung der PDFCreator Library (Verweis!) PDF-Dateien drucken.

Die erste Funktion schickt dabei einfach alle gefundenen Dateien eines beliebigen Verzeichnisses an die Funktion "PrintPDFFile", welche letztendlich die PDF Datei erstellt.

  1.  
  2. Public Sub PrintDirectory(ByVal aSourceDirectory As String, ByVal aFileFilter As String)
  3.  
  4. Dim lstFiles As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = _
  5. My.Computer.FileSystem.GetFiles(aSourceDirectory, FileIO.SearchOption.SearchAllSubDirectories, aFileFilter)
  6.  
  7. Dim fi As System.IO.FileInfo
  8. Dim fnnew As String
  9. Dim dirnew As String
  10.  
  11. Dim pdfjob As New PDFCreator.clsPDFCreator
  12.  
  13. If pdfjob.cStart("/NoProcessingAtStartup") = False Then
  14. MsgBox("Can't initialize PDFCreator.", vbCritical & vbOKOnly)
  15. Exit Sub
  16. End If
  17.  
  18. For Each fn As String In lstFiles
  19. ' Create new filename
  20. fi = My.Computer.FileSystem.GetFileInfo(fn)
  21. fnnew = fi.Name
  22. fnnew = Replace(fnnew, fi.Extension, "") ' Remove old extension. Don't add new extension!
  23. dirnew = fi.Directory.FullName & "\"
  24.  
  25. Me.PDFPrintFile(pdfjob, fi.FullName, fnnew, dirnew)
  26. Next
  27.  
  28. pdfjob.cClose()
  29. pdfjob = Nothing
  30. End Sub
  31.  
  1.  
  2. Public Sub PDFPrintFile(ByRef aPDFJob As PDFCreator.clsPDFCreator, ByVal aFilename As String, ByVal aOutputFilename As String, ByVal aOutputPath As String)
  3.  
  4. ' Exit it output filename already exists
  5. If System.IO.File.Exists(aOutputPath & aOutputFilename) Then
  6. Exit Sub
  7. End If
  8.  
  9. ' Create Outputdirectory if not existant
  10. If Not System.IO.Directory.Exists(aOutputPath) Then
  11. System.IO.Directory.CreateDirectory(aOutputPath)
  12. End If
  13.  
  14. With aPDFJob
  15. .cOption("UseAutosave") = 1
  16. .cOption("UseAutosaveDirectory") = 1
  17. .cOption("AutosaveDirectory") = aOutputPath
  18. .cOption("AutosaveFilename") = aOutputFilename
  19. .cOption("AutosaveFormat") = 0 ' 0 = PDF
  20. .cClearCache()
  21. End With
  22.  
  23. 'Print the document to PDF
  24. aPDFJob.cPrintFile(aFilename)
  25.  
  26. 'Wait until the print job has entered the print queue
  27. Do Until aPDFJob.cCountOfPrintjobs = 1
  28. ' My.Application.DoEvents.DoEvents()
  29. Loop
  30.  
  31. aPDFJob.cPrinterStop = False
  32.  
  33. 'Wait until PDF creator is finished then release the objects
  34. Do Until aPDFJob.cCountOfPrintjobs = 0
  35. ' My.Application.DoEvents()
  36. Loop
  37.  
  38. End Sub
  39.  

Aktualisierung vom 03.08.2009:

Wie ich heute leider mal wieder feststellen musste, funktioniert obiger Code bei einer großen Menge an umzuwandelnden Dateien nicht sonderlich.

Das unten aufgeführte "Modul" hat bei mir soeben 1400 Word-Dokumente erfolgreich in PDF umgenwandelt.

  1. Public Module modPrintPDF
  2.  
  3. Public Sub Main()
  4.  
  5. Dim strDir As String = "C:\Word\Serienbriefe\Einzelbriefe"
  6. PrintDirectoryPDF(strDir, "*.doc", strDir)
  7.  
  8. End Sub
  9.  
  10. Public Function PrintDirectoryPDF(ByVal aInputDirectory As String, ByVal aFilter As String, ByVal aOutputDirectory As String)
  11.  
  12. Dim lstFiles As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = _
  13. My.Computer.FileSystem.GetFiles(aInputDirectory, FileIO.SearchOption.SearchAllSubDirectories, aFilter)
  14.  
  15. Dim pdfc As New PDFCreator.clsPDFCreator
  16. pdfc.cStart(, True)
  17.  
  18. For Each fn As String In lstFiles
  19.  
  20. ' Generate New Filename
  21. Dim fi As New IO.FileInfo(fn)
  22. Dim strNewFilename As String = fi.Name
  23. strNewFilename = Replace(strNewFilename, fi.Extension, ".pdf")
  24.  
  25. ' Print File
  26. PrintPDF(pdfc, fn, aOutputDirectory, strNewFilename)
  27. Next
  28.  
  29. Return True
  30.  
  31. End Function
  32.  
  33. Public Function PrintPDF(ByRef aPDFCreator As PDFCreator.clsPDFCreator, ByVal aPDFFile As String, ByVal aOutputPath As String, ByVal aOutputFilename As String) As Integer
  34.  
  35. With aPDFCreator
  36. .cOption("UseAutosave") = 1
  37. .cOption("UseAutosaveDirectory") = 1
  38. .cOption("AutosaveFormat") = 0 ' 0 = PDF
  39. .cOption("AutosaveDirectory") = aOutputPath
  40. .cOption("AutosaveFilename") = aOutputFilename
  41. .cClearCache()
  42. .cPrintFile(aPDFFile)
  43. End With
  44.  
  45. End Function
  46.  
  47. End Module
  48.  

VB .NET - Strings mit Google uebersetzen

10. Jul 2008 23:47 (bearbeiten)

Das ganze habe ich aus dem Internet von Piyush Sha's Blog und noch etwas abgeändert, da der Code bei mir in der Praxis leider nicht funktioniert hat.

Erst die Sprach-Kürzel als Enum:

  1. Public Enum eLocales
  2. ar
  3. bg
  4. hr
  5. cs
  6. da
  7. nl
  8. en
  9. fi
  10. fr
  11. de
  12. l
  13. hi
  14. ja
  15. ko
  16. no
  17. pl
  18. pt
  19. ro
  20. ru
  21. es
  22. sv
  23. End Enum

Und hier die eigentliche Funktion die für die Übersetzung zuständig ist:

  1. ''' <summary>
  2. ''' Translates a text using the Google-API
  3. ''' </summary>
  4. ''' <param name="TextToTranslate"></param>
  5. ''' <param name="lngInput">Input Language</param>
  6. ''' <param name="lngOutput">Output Language</param>
  7. ''' <returns>The translated text</returns>
  8. ''' <remarks></remarks>
  9. Public Function TranslateText(ByVal TextToTranslate As String, ByVal lngInput As String, ByVal lngOutput As String) As String
  10. Dim result As String
  11.  
  12. Try
  13. Dim url As String = [String].Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}|{2}", TextToTranslate, lngInput, lngOutput)
  14. Dim webClient As New Net.WebClient()
  15. webClient.Encoding = System.Text.Encoding.Default
  16.  
  17. result = webClient.DownloadString(url)
  18.  
  19. Dim match As String = "id=result_box"
  20. Dim i As Integer = result.IndexOf(match) + 20
  21. Dim f As Integer = result.IndexOf(match) + 500
  22.  
  23. result = Mid(result, i, f)
  24. result = Mid(result, result.IndexOf(">") + 2, Len(result))
  25. result = Mid(result, 1, result.IndexOf("</div>"))
  26.  
  27. result = MakeHTMLValid(result)
  28. Catch ex As Exception
  29. result = String.Empty
  30. End Try
  31.  
  32. Return result
  33.  
  34. End Function

Update vom 28.02.2009:

Hier noch die kleine Hilfsfunktion um HTML-Zeichen einigermaßen valide zu machen. Ich weiß, dass das keine wirklich professionelle Lösung ist, daher habe ich den Code ursprünglich auch nicht gepostet. Da aber Nachfragen kamen, anbei als Ergänzung:

  1. ''' <summary>
  2. ''' Format HTML Code a bit
  3. ''' </summary>
  4. ''' <param name="aString">The text to format</param>
  5. ''' <returns></returns>
  6. ''' <remarks></remarks>
  7. Public Shared Function MakeHTMLValid(ByVal aString As String) As String
  8.  
  9. Dim result As String = aString
  10.  
  11. ' Replace Entities
  12. result = result.Replace("Ö", "&Ouml;")
  13. result = result.Replace("ö", "&ouml;")
  14. result = result.Replace("Ä", "&Auml;")
  15. result = result.Replace("ä", "&auml;")
  16. result = result.Replace("Ü", "&Uuml;")
  17. result = result.Replace("ü", "&uuml;")
  18. result = result.Replace("ß", "&szlig;")
  19.  
  20. result = result.Replace("€", "&euro;")
  21.  
  22. Return result
  23.  
  24. End Function

Get all tables from a sql server

28. Jun 2008 17:14 (bearbeiten)

This functions returns all sql tables from a given connection as a list of string.

  1. Public Shared Function GetTableList(ByVal strCon As String) As List(Of String)
  2. ' Create result
  3. Dim lstResult As New List(Of String)
  4.  
  5. Try
  6. Using con As New SqlClient.SqlConnection(strCon)
  7.  
  8. Try
  9. con.Open()
  10. Catch ex As Exception
  11. MsgBox(ex.Message, MsgBoxStyle.Critical)
  12. End Try
  13.  
  14. ' Create command and execute it
  15. Dim cmd As New SqlClient.SqlCommand("SELECT Table_Name FROM Information_Schema.Tables", con)
  16. Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader
  17.  
  18. ' Add all columns to our list
  19. Do While dr.Read
  20. lstResult.Add(dr("Table_Name").ToString)
  21. Loop
  22.  
  23. End Using
  24. Catch ex As Exception
  25. MsgBox(ex.Message, MsgBoxStyle.Critical)
  26. End Try
  27.  
  28. Return lstResult
  29. End Function

Tags ¦ , und

Get all columns from a sql table

28. Jun 2008 17:10 (bearbeiten)

Simple function to get all columns from a sql table.

Note: You should prepare the sql statement and check it for injections...

  1.  
  2. Public Shared Function GetColumnList(ByVal strCon As String, ByVal aDatasetName As String, ByVal aTablename As String) As List(Of String)
  3. Dim lstResult As New List(Of String)
  4. Using con As SqlConnection = New SqlConnection(strCon)
  5. Try
  6. con.Open()
  7. Dim ds As New DataSet(aDatasetName)
  8. Dim da As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM " & aTablename, con)
  9. da.Fill(ds, aTablename)
  10. For Each dt As DataTable In ds.Tables
  11. For Each dc As DataColumn In dt.Columns
  12. lstResult.Add(dc.Caption)
  13. Next
  14. Next
  15. Catch ex As Exception
  16. MsgBox(ex.Message, MsgBoxStyle.Critical)
  17. Return Nothing
  18. End Try
  19. End Using
  20. Return lstResult
  21. End Function
  22.  

Tags ¦ , und

Get all columns from a xml file

28. Jun 2008 17:06 (bearbeiten)

The following function returns all columns from a xml file as a list of string.

  1.  
  2. Public Shared Function GetColumnList(ByVal aFilename As String) As List(Of String)
  3. If Not File.Exists(aFilename) Then
  4. Throw New System.IO.FileNotFoundException("File not found!", aFilename)
  5. Exit Function
  6. End If
  7. Dim lstResult As New List(Of String)
  8. Dim ds As New DataSet
  9. Try
  10. ds.ReadXml(aFilename, XmlReadMode.InferSchema)
  11. For Each dt As DataTable In ds.Tables
  12. For Each dc As DataColumn In dt.Columns
  13. lstResult.Add(dc.Caption)
  14. Next
  15. Next
  16. Catch ex As Exception
  17. MsgBox(ex.Message, MsgBoxStyle.Critical)
  18. End Try
  19. Return lstResult
  20. End Function
  21. End Class
  22.  

Tags ¦ , , und

Get all tables from a XML File

28. Jun 2008 17:04 (bearbeiten)

The following function returns all tables in a list of string from a xml file.

  1.  
  2. Public Shared Function GetTableList(ByVal aFilename As String) As List(Of String)
  3. If Not File.Exists(aFilename) Then
  4. Throw New System.IO.FileNotFoundException("File not found!", aFilename)
  5. Exit Function
  6. End If
  7. Dim lstResult As New List(Of String)
  8. Dim ds As New DataSet
  9. Try
  10. ds.ReadXml(aFilename, XmlReadMode.InferSchema)
  11. For Each dt As DataTable In ds.Tables
  12. lstResult.Add(dt.TableName)
  13. Next
  14. Catch ex As Exception
  15. MsgBox(ex.Message, MsgBoxStyle.Critical)
  16. End Try
  17. Return lstResult
  18. End Function
  19.  

Tags ¦ , , und

VB .NET ReportViewer

28. Jun 2008 17:01 (bearbeiten)

Mit der folgende Methoden lässt sich ein ReportViewer mit Daten aus einem XML File befüllen und anzeigen.
Den Report an sich kann man bequem im Visual Studio erstellen und abspeichern. Databindings und dergleichen sind nicht notwendig.

Die untere Methode ermöglicht das Speichern eines Reports als PDF-Datei.

  1. Public Sub ShowReportViewer(ByVal aXMLFilename As String, ByVal aReportFilename As String, _
  2. ByVal aDatasetName As String, ByVal aTableName As String, _
  3. ByVal aDataTableIndex As Integer, _
  4. Optional ByVal DoSaveReport As Boolean = False, Optional ByVal SaveReportAsFilename As String = "")
  5.  
  6. If Not System.IO.File.Exists(aXMLFilename) Then
  7. MsgBox(String.Format("Die XML Datenquelle ""{0}"" wurde nicht gefunden!", aXMLFilename), MsgBoxStyle.Critical)
  8. Exit Sub
  9. End If
  10.  
  11. If Not System.IO.File.Exists(aReportFilename) Then
  12. MsgBox(String.Format("Die Report Vorlage ""{0}"" wurde nicht gefunden!", aReportFilename), MsgBoxStyle.Critical)
  13. Exit Sub
  14. End If
  15.  
  16. ' Create new DataSet and load Data from aXMLFilename into it
  17. Dim ds As New DataSet()
  18. ds.DataSetName = aDatasetName
  19. ds.ReadXml(aXMLFilename)
  20.  
  21. ' Create Form
  22. Dim frm As New Windows.Forms.Form
  23. frm.StartPosition = Windows.Forms.FormStartPosition.CenterParent
  24. frm.Height = 400
  25. frm.Width = 400
  26.  
  27. ' Create Report Data Source
  28. ' The most important part here is aDatasetName & "_" & aTablename
  29. Dim rds As New Microsoft.Reporting.WinForms.ReportDataSource(aDatasetName & "_" & aTableName, ds.Tables(aDataTableIndex))
  30.  
  31. ' Create ReportViewer
  32. Dim rv As New Microsoft.Reporting.WinForms.ReportViewer
  33. rv.Dock = Windows.Forms.DockStyle.Fill
  34.  
  35. ' Add ReportViewer to Form
  36. frm.Controls.Add(rv)
  37.  
  38. ' Load Report Definition File
  39. Dim fs As New System.IO.FileStream(aReportFilename, IO.FileMode.Open)
  40. rv.LocalReport.LoadReportDefinition(fs)
  41.  
  42. ' Add Report Data Source
  43. rv.LocalReport.DataSources.Clear()
  44. rv.LocalReport.DataSources.Add(rds)
  45. rv.RefreshReport()
  46. ' Save Report as File?
  47. If DoSaveReport Then
  48. SaveReport(rv.LocalReport, SaveReportAsFilename)
  49. End If
  50. ' Finally Show Form
  51. frm.ShowDialog()
  52. End Sub
  53.  
  1.  
  2. Public Sub SaveReport(ByVal aLocalReport As Microsoft.Reporting.WinForms.LocalReport, ByVal aFilename As String, Optional ByVal aRenderFormat As String = "PDF")
  3. ' Todo: Check if aFilename already exists and prompt user to overwrite/skip
  4. Dim warnings As Microsoft.Reporting.WinForms.Warning() = Nothing
  5. Dim streamids As String() = Nothing
  6. Dim mimeType As String = Nothing
  7. Dim encoding As String = Nothing
  8. Dim extension As String = Nothing
  9. Dim bytes As Byte()
  10. Try
  11. bytes = aLocalReport.Render(aRenderFormat, Nothing, mimeType, encoding, extension, streamids, warnings)
  12. Dim fs As New IO.FileStream(aFilename, System.IO.FileMode.Create)
  13. fs.Write(bytes, 0, bytes.Length)
  14. fs.Close()
  15. Catch ex As Exception
  16. ' AddToLog(ex.Message)
  17. End Try
  18. End Sub
  19.  

Beispielaufruf:

  1.  
  2. Public Sub Test()
  3. ShowReportViewer("C:\test.xml", "C:\repMain.rdlc", "NewDataSet", "Table", 0, True, "C:\test.pdf")
  4. End Sub
  5.