I need help in writing justified using OpenXML in Word. My application does handle some data and should afterwards write the output (which are texts) in a .docx-file (Word file).
Since I am new to OpenXML and since I do not want to reply on 3rd party plugins I want to stick to the simplest solution possible.
After my application processed the data, I have for example three texts:
Text1="Automation code 83743 on 2022-08-04 # 091433"
Text2="The power of the three samples provides no significant changes during the last period of test"
Text3="Sample A=8458349mg/L, Sample B=849922mg/L,....Sample Z48=798993mg/L"
I want the following:
Text1 should be written simply in bold.
Text2 should be written simply in bold too.
Text3 should be written as justified text without being bold.
Currently my code looks like this (as the documentation I found uses the same sort of coding):
Dim WordDocumentPath As String = "C:\\Text.docx"
'Create a document to work in
Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(WordDocumentPath, WordprocessingDocumentType.Document)
' Add a main document part.
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
' Create the document structure and add some text.
mainPart.Document = New Document()
Dim body As Body = mainPart.Document.AppendChild(New Body())
Dim para As Paragraph = body.AppendChild(New Paragraph())
Dim run As Run = para.AppendChild(New Run())
'Write bold
Dim runProperties As RunProperties = run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text(Text1))
run.AppendChild(New Paragraph)
'Write bold
run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text(Text2))
run.AppendChild(New Paragraph)
'Write justified
run.AppendChild(New Text(Text3))
run.AppendChild(New Paragraph)
Next
End Using
I have the problem that using my code, I am somehow not able to write in justified. Is there a nicer way to write my code (in regards to optimization)?
Try the following code.Use Justification and ParagraphProperties.
Dim WordDocumentPath As String = "C:\\Text.docx"
'Create a document to work in
Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(WordDocumentPath, WordprocessingDocumentType.Document)
' Add a main document part.
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
' Create the document structure and add some text.
mainPart.Document = New Document()
Dim body As Body = mainPart.Document.AppendChild(New Body())
Dim para As Paragraph = body.AppendChild(New Paragraph())
Dim run As Run = para.AppendChild(New Run())
Dim justification As Justification = New Justification()
justification.Val = JustificationValues.Center
Dim paragraphProperties1 As ParagraphProperties = New ParagraphProperties
paragraphProperties1.Append(justification)
Dim paragraph As Paragraph = New Paragraph
paragraph.ParagraphProperties = paragraphProperties1
'Write bold
Dim runProperties As RunProperties = run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text("11111111111111111"))
run.AppendChild(New Paragraph)
'Write bold
run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text("22222222222222222222"))
run.AppendChild(New Paragraph)
'Write justified
run.AppendChild(New Text("33333333333333333333"))
run.AppendChild(paragraph)
wordDocument.Close()
End Using
Related
I'm trying to convert some itextsharp code to use itext7 which stamps text on each page of a pdf at rotate 90 degrees. Unfortunately all the examples I can find are in c# and while I can use an online translator I'm having difficulties with this one.
The below code stamps my text on at the specified coords on each page of a given pdf:
Shared Sub itext7_stamp_text_on_pdf(mypdfname As String, myfoldername As String)
Dim src As String = myfoldername & "\" & mypdfname
Dim dest As String = myfoldername & "\Stamped " & mypdfname
Dim pdfDoc As PdfDocument = New PdfDocument(New PdfReader(src), New PdfWriter(dest))
Dim document As Document = New Document(pdfDoc)
Dim canvas As PdfCanvas
Dim n As Integer = pdfDoc.GetNumberOfPages()
For i = 1 To n
Dim page As PdfPage = pdfDoc.GetPage(i)
canvas = New PdfCanvas(page)
With canvas
.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 12)
.BeginText()
.MoveText(100, 100)
.ShowText("SAMPLE TEXT 100,100")
.EndText()
End With
Next
pdfDoc.Close()
End Sub
... but I can't see a way of rotating it to 90 degrees.
There's an example here if you use a paragraph:
https://kb.itextpdf.com/home/it7kb/examples/itext-7-building-blocks-chapter-2-rootelement-examples#iText7BuildingBlocksChapter2:RootElementexamples-c02e14_showtextaligned
... but I can't seem to translate this to vb.net. I can specify where the errors I get are, but I thought I'd be better asking this general question first in case there's a way to do this without using a paragraph.
Can anyone help please?
Thanks!
Well, after some more digging this code seems to work OK on the rotation part:
Dim pdf As New PdfDocument(New PdfReader(inpdf), New PdfWriter(outpdf))
Dim document As New Document(pdf)
document.ShowTextAligned("This is some test text", 400, 750, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0.5F * CSng(Math.PI))
document.Close()
End Sub
.... but it gets hidden behind existing content, so I need a way to make sure it's set to over content.
I am having problems trying to read a text file which is open by another process.
After searching SO I have found a few similar questions albeit in C# and nor VB.Net which seem to refer to the fact that FileShare.ReadWrite is the key to getting this to work but yet I am still struggling with it.
This is what I have so far but nothing is appearing in TextBox1.
Dim logFileStream As FileStream = New FileStream("C:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim logFileReader As StreamReader = New StreamReader(logFileStream)
While Not logFileReader.EndOfStream
Dim line As String = logFileReader.ReadLine()
TextBox1.Text = line
End While
logFileReader.Close()
logFileStream.Close()
My goal is to just use the last 2 lines of what's in the file c:\test.txt and display those contents into a Label but I guess I first need to read and show the content before I can start to look at just extracting the last 2 lines.
Update:
After re-visiting the MS Docs, I have rearranged the code as below and I can now seem to read the open file into a TextBox
Dim strLogFilePath As String
Dim LogFileStream As FileStream
Dim LogFileReader As StreamReader
Dim strRowText As String
strLogFilePath = "C:\DSD\DSDPlus.srt"
LogFileStream = New FileStream(strLogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
LogFileReader = New StreamReader(LogFileStream)
strRowText = LogFileReader.ReadToEnd()
TextBox1.Text = strRowText
LogFileReader.Close()
LogFileStream.Close()
I am a student in computer science and for a project I need to be able to read from a text file in a way that each line is assigned to a space within an array. This should happen so that each line of text file is read in the order that it appears in the text file. I would also appreciate any methods of writing to a text file as well.
If this question is already explained, could you please direct me to the existing answer.
Things to note:
1) I am coding in a console application in VB.NET
2) I am relatively new at coding
You can do it like this:
Dim sFile As String = "D:\File.txt"
Dim aLines As String() = System.IO.File.ReadAllLines(sFile)
System.IO.File.WriteAllLines(sFile, aLines)
Here's a sample from the official documentation:
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText() As String = {"Hello", "And", "Welcome"}
File.WriteAllLines(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
Console.WriteLine(s)
Next
End Sub
End Class
Remarks
This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
Module Module1
Sub Main()
'Declare four variables
Dim oReader As New System.IO.StreamReader(".\archive01.txt") 'This file has to exist in the aplication current directory.
Dim oWriter As New System.IO.StreamWriter(".\archive02.txt") 'This file will be created by the software.
Dim oArray() As String = {}
Dim oString As String = Nothing
'For reading from .\archive01.txt and to load in oArray().
oString = oReader.ReadLine
While Not oString Is Nothing
If UBound(oArray) = -1 Then 'Ubound = Upper Bound, also exist LBound = Lower Bound.
ReDim oArray(UBound(oArray) + 1)
Else
ReDim Preserve oArray(UBound(oArray) + 1)
End If
oArray(UBound(oArray)) = New String(oString)
oString = oReader.ReadLine
End While
oReader.Close()
'For writing from oArray() to .\archive02.txt.
For i = 0 To oArray.Count - 1 Step 1
oWriter.WriteLine(oArray(i))
Next
oWriter.Close()
End Sub
End Module
Hi, try with this code. It works well. I hope that this helps to you to learn how to do this kind of things. Thank you very much. And happy codding!. :)
FIRST PROBLEM:
I am looking for an easiest way to read multiple text files at one time and extract all the duplicate lines from each text file and copy those duplicate lines to a new text file with headings representing name of parent text file. I am dealing with more than 20 text files at a time and it is a mess to go through each one by one. Secondly, I am dealing with large / heavy file (more or less 30,000 lines in each file) .. I am currently using a program with "Stream Reader" and "Stream Writer" and I prefer to have the same approach for my understanding. OR any new and easy way is Welcome !!
SECOND PROBLEM:
I want to compare 2 text files and get the duplicate lines on to a new text file. I don't want to remove/delete/overwrite: Just to copy them across to a new text file.
Please use openfiledialog and savefiledialog for the files.
Thanks a lot in advance.
Best Regards
VB_Learner
Dim Dim optxtfile As New OpenFileDialog
optxtfile.RestoreDirectory = True
optxtfile.Multiselect = False
optxtfile.Filter = "txt files (*.txt)|*.txt"
optxtfile.FilterIndex = 1
optxtfile.ShowDialog()
If (Not optxtfile.FileName = Nothing) Then
Dim lines As New List(Of String)
Using sr As New System.IO.StreamReader(optxtfile.FileName)
While sr.Peek <> -1
Dim line As String = sr.ReadLine()
Dim isNew As Boolean = True
For Each dupl As String In lines
If (dupl = line) Then isNew = False
Next
If (isNew) Then lines.Add(sr.ReadLine())
End While
End Using
Dim svDir As String
If (My.Computer.FileSystem.FileExists(optxtfile.FileName)) Then
My.Computer.FileSystem.DeleteFile(optxtfile.FileName)
svDir = optxtfile.filename
Dim svtxtfile As New SaveFileDialog
svtxtfile.RestoreDirectory = True
svtxtfile.Filter = "txt files (*.txt)|*.txt"
svtxtfile.FilterIndex = 1
svtxtfile.ShowDialog()
If (svtxtfile.FileName = Nothing) Then
svDir = optxtfile.FileName
Else
svDir = svtxtfile.FileName
End If
End If
Using write2text As New System.IO.StreamWriter(svDir)
For Each line As String In lines
write2text.WriteLine(line)
Next
End Using
End If
End Sub
If i have information (for example a name) in a label on a form in Visual Basic, how do I save this information in a .txt file?
Thanks
You can use the classes in the System.IO namespace. Look at File and its methods.
This example uses one overload of WriteAllText:
File.WriteAllText("Path To Text File.txt", myLabel.Text)
It will write the text value of the myLabel control to the specifies text file.
You use StreamWriter to do that. Here's an example:
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
If you want to know how to read from txt files, here's a example code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)
You can use file system object for ealier versions of Visual basic.
' VBScript
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine(label.caption)
MyFile.Close
http://msdn.microsoft.com/en-us/library/z9ty6h50(VS.85).aspx
or
Sub Create_File()
Dim fso, txtfile
Set fso = CreateObject("Scripting.FileSystemObject")
Set txtfile = fso.CreateTextFile("c:\testfile.txt", True)
txtfile.Write (lable.caption) ' Write a line.
' Write a line with a newline character.
txtfile.WriteLine("Testing 1, 2, 3.")
' Write three newline characters to the file.
txtfile.WriteBlankLines(3)
txtfile.Close
End Sub
http://msdn.microsoft.com/en-us/library/aa263346(VS.60).aspx
Put it directly into the place you needed
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("filename.txt", True)
file.WriteLine("Your Text Here~")
file.Close()