How to convert visual foxpro 6 report to word - visual-foxpro

I have used following code to show a report.
select mem_no,com_name,owner,owner_cate,iif(empty(photo),"c:\edrs\memphoto\void.JPG",iif(file(photo),photo,"c:\edrs\memphoto\void.JPG")) as photo from own1 into curs own
REPO FORM c:\edrs\reports\rptsearch.frx TO PRINT PREVIEW NOCONS
Here rptsearch.frx contains some image. The following code export data to excel except image.
COPY TO "c:\documents and settings\administrator\desktop\a.xls" TYPE XLS
In case of image it shows only the path name. Now I need to know how I can convert this report in word so that I can have the images in the word report.

It looks like that you are creating a simple list with pictures. One of the easiest ways to do that is to use automation. ie:
Select mem_no,com_name,owner,owner_cate,;
iif(Empty(photo) Or !File(photo),"c:\edrs\memphoto\void.JPG",photo) As photo ;
from own1 ;
into Curs crsData ;
nofilter
#Define wdWord9TableBehavior 1
#Define wdAutoFitWindow 2
#Define wdStory 6
#Define wdCollapseEnd 0
#Define wdCellAlignVerticalCenter 1
#Define CR Chr(13)
Local Array laCaptions[5]
laCaptions[1] = 'Mem No'
laCaptions[2] = 'Com Name'
laCaptions[3] = 'Owner'
laCaptions[4] = 'Owner Cate'
laCaptions[5] = 'Photo'
Local nRows, nCols, ix
nRows = Reccount('crsData')+1
nCols = Fcount('crsData')+1
oWord = Createobject('Word.Application')
With m.oWord
oDocument = .Documents.Add
With m.oDocument.Tables.Add( m.oWord.Selection.Range, m.nRows, m.nCols)
.BorderS.InsideLineStyle = .F.
.BorderS.OutsideLineStyle = .F.
For ix=1 To Alen(laCaptions)
**** Add captions *****
.Cell(1,m.ix).Range.InsertAfter( laCaptions[m.ix] )
Endfor
Select crsData
Scan
For ix=1 To Fcount()-1 && last one is photo path
**** Add values to the different cells *****
.Cell(Recno()+1,m.ix).Range.InsertAfter( Eval(Field(m.ix)) )
Endfor
lcPhoto = crsData.photo
If File(m.lcPhoto) && Add photo if any
oDocument.InlineShapes.AddPicture( m.lcPhoto, .T., .T.,;
.Cell(Recno()+1,Fcount()).Range)
Endif
.Rows(Recno()+1).Cells.VerticalAlignment = wdCellAlignVerticalCenter
Endscan
Endwith
.Visible = .T.
Endwith
However, sending data to word this way would suffer from performance if you have many rows. You can use this for small data like an employee table or so. With larger data, instead of using automation, you could simply create an HTML document and word would open an HTML document.

There is no native way to do it. I would investigate FoxyPreviewer and use that to report to RTF, which Word can open.
Or do it the other way round with a mail merge in Word.

In addition to FoxyPreviewer, you could also use OLE Office automation to programmatically build the report. There are numerous examples online, and even a book, Microsoft Office Automation, written by Tamar E. Granor & Della Martin.
I have not done a lot with automation, only enough to get it basically verify it works, and discover it was very slow for what I was attempting to do.

Related

How to send color images with ESC/POS?

I have an Epson CW-C6000 that I'm trying to control with ESC commands. I've gotten text to print, so I know I have the IP address, port, etc correct but cannot for the life of me get an image printed.
Here is my code (running from a Ruby on Rails server, with most of the image truncated):
streamSock = TCPSocket.new( "X.X.X.X", 9100 )
str = "~DYR:PRODIMG,B,P,183208,0,89504E470D...4AE426082" + "^XA" + "^FO150,150^IMR:PRODIMG.PNG^FS" + "^XZ"
streamSock.send( str , 0)
streamSock.close
The image is a .png I converted to hexadecimal with this site:
http://tomeko.net/online_tools/file_to_hex.php?lang=en
I'm mostly using page 10 of this PDF for reference:
https://files.support.epson.com/pdf/pos/bulk/esclabel_apg_en_forcw-c6000series_reve.pdf
Does anyone have a hint? Epson support staff was spectacularly unhelpful.
Also I'm sorry if my formatting is bad; I'm new here and will happily edit my post if something is wrong.
Alright I finally got it working. The command for printing a color .PNG is this:
~DYE:[Image Name].PNG,p,p,[Image Size],0,:B64:[Base64 String]:[CRC]
Things that tripped me up:
-You seem to need the .PNG extension on the file name, even though the Epson manual doesn't show that.
-[Image Size] is the number of characters in the Base64 string, even though the Epson manual says it should be the size of the original .PNG image file. If this is wrong the printer will hang and no longer accept input of any kind until restarted.
-There may be other options, but I could only get it working with a CRC of the hex CRC-16/XMODEM type.
Thanks to K J for his/her suggestions and coming along with me!
Perhaps this material can be used as an additional reference.
They seem to have a completely different command/data format than ESC/POS.
ESC/Label Command Reference Guide
Page 12
1.3.4 About Saving the Graphics and Label Formats in the Printer
With ESC/Label command, you can save graphics and label formats in the printer. The printer has a file system. Data saved in the printer is handled as files and is managed in the following way.
The file system does not have a hierarchy.
The printer has a non-volatile saving device, such as Flash ROM, and a volatile saving device, such as RAM, and different drive letters are allocated for each device.
Files are designated as
"<drive letter> colon <:> <file name> dot <.> <extension>".
Page 40-41
2.8 Printing Graphics
...Details have been omitted. Please refer to the actual document...
2.8.1 Registering a Graphic in a Printer and Printing It
...Pick up some from the content. Please refer to the actual document...
Delete the files that remain in the printer (^ID command).
Register the graphic in the printer (~DY command).
When registering a color graphic, you can use the PNG format. When registering a monochrome graphic, you can register the PNG format or the GRF format.
PNG format Monochrome and color graphics
GRF format Monochrome graphics
The reason to execute the step 1.
To ensure capacity of the storage memory necessary for print which application will perform.
2.8.2 Embedding a Graphic in the Field and Printing It
...Details have been omitted. Please refer to the actual document...
In Addition:
Page 104-106
~DY
[Name]
Save File
[Format]
~DY d: o ,f ,x ,t ,w ,data
...A table detailing the parameters is due, but omitted...
[Function]
...Further detailed explanations and figures of functions and parameters are due, but omitted...
Graphic data is handled as follows.
If the data format is binary, you can use any binary data as Parameter data. At this time, the size of Parameter data must be matched to the size specified in Parameter t.
If the data format is a hexadecimal character string, one character from 1. to 3. below is used as Parameter data. At this time, the size of Parameter data written in binary must be matched to the size specified in Parameter t.
0 to 9, A to F, and a to f in ASCII can be used as hexadecimal graphic data.
ASCII comma <,>, the parameter separator character, is used to separate lines. If a comma is input, processing is carried out as if ASCII 0 was input for the remainder of the line.
G to Y and g to z in ASCII can be used as repetition characters. For example, if I9 is input, processing is carried out as if 999 were input. The following table indicates the number of repetitions.
...Characters and repeat specified number of times table omitted...
Looking at the contents of this Technical Reference Guide, it seems that you can register images with tools instead of commands.
CW-C6000/C6500 Series Technical Reference Guide
Page 173-174
And page 288 outlines the Epson Inkjet Label Printer SDK and also describes the existence of sample programs.
#Farmbot26. I have been attempting this same using vb.Net and as you noted Epson support is not helpful. I'm not sure if it's the actual image data that is wrong, CRC, or the ZPL code as nothing helps. Here's 2 examples that have not worked.
`Dim binaryData As Byte() = System.IO.File.ReadAllBytes(txtPNGFile.Text)
zplImageData = Convert.ToBase64String(binaryData)
crc = calcrc(binaryData, binaryData.Length).ToString("X4")
Dim zplToSend As String = "~DYE:" & Path.GetFileName(txtPNGFile.Text).ToUpper & ",P,P," & zplImageData.Length & ",0,:B64:" & zplImageData & ":" & crc & "^XZ"`
`Dim binaryData As Byte() = System.IO.File.ReadAllBytes(txtPNGFile.Text)
crc = calcrc(binaryData, binaryData.Length).ToString("X4") 'Calculate CRC
zplImageData = BitConverter.ToString(binaryData).Replace("-", "")
Dim zplToSend As String = "~DYE:" & Path.GetFileName(txtPNGFile.Text).ToUpper & ",A,P," & zplImageData.Length & ",0,:B64:" & zplImageData & ":" & crc & "^XZ"`
This is the CRC example I have.
`Function calcrc(ByVal data() As Byte, ByVal count As Integer) As Integer
Dim crc As Integer = 0
For Each b As Byte In data
Dim d As Integer = CInt(b)
crc = crc Xor (d << 8)
For j = 0 To 7
If ((crc And &H8000) <> 0) Then
crc = (crc << 1) Xor &H1021
Else
crc = (crc << 1)
End If
Next
Next
Return crc And &HFFFF
End Function`
I have figured out another solution. Save the PNG Image using the Binary data. I found this when reading the Saved Backup file of Image data using the Epson Settings Utility.
~DYE:FILENAME.PNG,B,P,BINARYFILESIZE,0, BINARYIMGDATA
` Try
Dim binaryData As Byte() = System.IO.File.ReadAllBytes(txtPNGFile.Text)
Dim client As System.Net.Sockets.TcpClient = New System.Net.Sockets.TcpClient()
client.Connect(IP_TextBox1.Text.Replace(" ", ""), txtPort.Text)
Dim writer As System.IO.StreamWriter = New System.IO.StreamWriter(client.GetStream(), Encoding.UTF8)
Using mStream As New MemoryStream(binaryData)
Dim zplToSend As String = "~DYE:" & Path.GetFileName(txtPNGFile.Text).ToUpper & ",B,P," & mStream.Length & ",0,"
writer.Write(zplToSend)
writer.Flush()
mStream.WriteTo(client.GetStream())
writer.Flush()
End Using
writer.Close()
client.Close()
MsgBox("Send Complete", MsgBoxStyle.OkOnly, "Complete")
Catch ex As Exception
MsgBox(ex.Message.ToString, MsgBoxStyle.OkOnly, "ERROR")
End Try`
You can also open the image file in an IMAGE object and resize it as needed. I had to do this for the label size of the printer.

Stata esttab/LaTeX Error: Extra alignment tab has been changed to \cr

Combining and modifying this code (http://www.stata.com/statalist/archive/2012-11/msg00756.html) and this code (http://www.stata.com/statalist/archive/2009-02/msg00023.html), I try to use esttab (part of estout) in Stata to export a file that can be compiled in LaTeX. A real application of this might involve a complicated summary statistics table where one is pulling the statistics from several different sources and thus needs to utilize matrices. I am getting an error, however, in LaTeX when I compile. The error is:
Extra alignment tab has been changed to \cr.
Stata code:
clear all
eststo clear
mat A = (1,2\5,6)
mat coln A = male:1979 male:2007
mat rown A = mystat
ereturn post
estadd matrix B = A'
eststo MaleLabel
mat A = (3,4\7,8)
mat coln A = female:1979 female:2007
mat rown A = mystat
ereturn post
estadd matrix B = A'
eststo FemaleLabel
esttab MaleLabel FemaleLabel using "esttab.tex", ///
cell((B["1979"]B["2007"])) booktabs ///
mgroups("Male" "Female", pattern(1 1) prefix(\multicolumn{#span}{c}{) suffix(}) span erepeat(\cmidrule(lr){#span})) ///
noobs replace nomtitles nonum
LaTeX code:
\documentclass[12pt]{article}
\usepackage{booktabs}
\begin{document}
\begin{table}[htbp]
\begin{center}
\input{esttab}
\end{center}
\end{table}
\end{document}
The file that is produced from esttab is:
{
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\begin{tabular}{l*{2}{c}}
\toprule
&\multicolumn{2}{c}{Male} &\multicolumn{2}{c}{Female}\\\cmidrule(lr){2-3}\cmidrule(lr){4-5}
& 1979& 2007& 1979& 2007\\
\midrule
mystat & 1& 2& 3& 4\\
mystat & 5& 6& 7& 8\\
\bottomrule
\end{tabular}
}
Now, I can get things to work if I tweak this line:
\begin{tabular}{l*{2}{c}}
to be:
\begin{tabular}{l*{2}{cc}}
(I added an extra c.)
But I only know how to do this manually. What can I change in the Stata code to make this happen automatically?
add this simple option to your estab code
prehead({\begin{tabular}{l*{2}{cc}}\toprule)
and you are all set my man!

COPY TO excel Sheet in foxpro

Is their any command in Foxpro that convert the DBF into a particular excel sheet.
I have three DBF(dbf_1, dbf_2, dbf_3). My current program convert the file using copy to "filename.xls" type fox2x and then I will manually copy the consolidate all the sheet into one excel. For me, this method I using is alright but what if their are 20 or more dbf that I will consolidate. Is their any command in foxpro that convert the dbf's into one excel file. I already use the foxpro Automation but it is to slow.
No there isn't.
Also "copy to ... type fox2x". although better than many other type selections (such as csv and xls) should not be chosen when there are better ways.
You are saying automation is slow, but don't know if you are really finding automation slow, or if you have tried it in the ways that you shouldn't use to transfer data to Excel. The sample below, use one of the variations of my "vfp2excel" function and automation. It transfers sample Customer, Employee, Orders, OrdItems and Products data in 2.5 seconds on my machine. If you really meant it as slow then no dice, otherwise here is the sample:
* These represent complex SQL as a sample
Select emp_id,First_Name,Last_Name,;
Title,Notes ;
from (_samples+'\data\employee') ;
into Cursor crsEmployee ;
readwrite
Replace All Notes With Chrtran(Notes,Chr(13)+Chr(10),Chr(10))
Select cust_id,company,contact,Title,country,postalcode ;
from (_samples+'\data\customer') ;
into Cursor crsCustomer ;
nofilter
Select * ;
from (_samples+'\data\orders') ;
into Cursor crsOrders ;
nofilter
Select * ;
from (_samples+'\data\orditems') ;
into Cursor crsOrderDetail ;
nofilter
Select * ;
from (_samples+'\data\products') ;
into Cursor crsProducts ;
nofilter
* Now we want to get these on 3 sheets
* Sheet1: Employees only
* Sheet2: Customers only
* Sheet3: Orders, ordItems, Products layed out horizontally
Local oExcel
oExcel = Createobject("Excel.Application")
With oExcel
.DisplayAlerts = .F.
.Workbooks.Add
.Visible = .T.
With .ActiveWorkBook
For ix = 1 To 3 && We want 3 Sheets
If .sheets.Count < m.ix
.sheets.Add(,.sheets(.sheets.Count)) && Add new sheets
Endif
Endfor
* Name the sheets
.WorkSheets(1).Name = "Employees"
.WorkSheets(2).Name = "Customers"
.WorkSheets(3).Name = "Order, OrderDetail, Products" && max sheetname is 31 chars
* Start sending data
* First one has headers specified
VFP2Excel('crsEmployee', .WorkSheets(1).Range("A1"), ;
"Id,First Name,Last Name,Employee Title,Comments about employee" ) && To sheet1, start at A1
VFP2Excel('crsCustomer', .WorkSheets(2).Range("A1") ) && To sheet2, start at A1
VFP2Excel('crsOrders', .WorkSheets(3).Range("A1") ) && To sheet3, start at A1
* Need to know where to put next
* Leave 2 columns empty - something like 'G1'
lcRange = _GetChar(.WorkSheets(3).UsedRange.Columns.Count + 3) + '1'
* To sheet3, start at next to previous
VFP2Excel('crsOrderDetail', .WorkSheets(3).Range(m.lcRange) )
lcRange = _GetChar(.WorkSheets(3).UsedRange.Columns.Count + 3) + '1'
* To sheet3, start at next to previous
VFP2Excel('crsProducts', .WorkSheets(3).Range(m.lcRange) )
#Define xlJustify -4130
#Define xlTop -4160
* I just happen to know notes in at column 5 from SQL
* No need to query from excel to keep code simple
* Lets format that column specially instead of leaving
* at the mercy of Excel's autofitting
.WorkSheets(1).UsedRange.VerticalAlignment = xlTop && set all to top
With .WorkSheets(1).Columns(5)
.ColumnWidth = 80 && 80 chars width
.WrapText = .T.
* .HorizontalAlignment = xlJustify && doesn't work good always
Endwith
* Finally some cosmetic stuff
For ix=1 To 3
With .WorkSheets(m.ix)
.Columns.AutoFit
.Rows.AutoFit
Endwith
Endfor
.WorkSheets(1).Activate
Endwith
Endwith
* Author: Cetin Basoz
* This is based on earlier VFP2Excel function codes
* that has been published on the internet, at various sites
* since 2001. Not to be messed with others' code who named the same but has
* nothing to do with the approaches taken here (unless copy & pasted and claimed
* to be their own work, < s > that happens).
Procedure VFP2Excel(tcCursorName, toRange, tcHeaders, tnPrefferredWidthForMemo)
* tcCursorName
* toRange
* tcHeaders: Optional. Defaults to field headers
* tnPrefferredWidthForMemo: Optional. Default 80
* Function VFP2Excel
tcCursorName = Evl(m.tcCursorName,Alias())
tnPrefferredWidthForMemo = Evl(m.tnPrefferredWidthForMemo,80)
Local loConn As AdoDB.Connection, loRS As AdoDB.Recordset,;
lcTemp,lcTempDb, oExcel,ix, lcFieldName, lcHeaders
lnSelect = Select()
lcTemp = Forcepath(Sys(2015)+'.dbf',Sys(2023))
lcTempDb = Forcepath(Sys(2015)+'.dbc',Sys(2023))
Create Database (m.lcTempDb)
Select * From (m.tcCursorName) Into Table (m.lcTemp) Database (m.lcTempDb)
Local Array aMemo[1]
Local nMemoCount
nMemoCount = 0
lcHeaders = ''
For ix = 1 To Fcount()
lcFieldName = Field(m.ix)
If Type(Field(m.ix))='M'
nMemoCount = m.nMemoCount + 1
Dimension aMemo[m.nMemoCount]
aMemo[m.nMemoCount] = m.ix
Replace All &lcFieldName With Chrtran(&lcFieldName,Chr(13)+Chr(10),Chr(10))
Endif
lcHeaders = m.lcHeaders + Iif(Empty(m.lcHeaders),'',',')+Proper(m.lcFieldName)
Endfor
tcHeaders = Evl(m.tcHeaders,m.lcHeaders)
Use In (Juststem(m.lcTemp))
Close Databases
Set Database To
loStream = Createobject('AdoDb.Stream')
loConn = Createobject('ADODB.Connection')
loRS = Createobject("ADODB.Recordset")
loConn.ConnectionString = "Provider=VFPOLEDB;Data Source="+m.lcTempDb
loConn.Open()
loRS = loConn.Execute("select * from "+m.lcTemp)
loRS.Save( loStream )
loRS.Close
loConn.Close
Erase (m.lcTemp)
* Use first row for headers
Local Array aHeader[1]
loRS.Open( loStream )
toRange.Offset(1,0).CopyFromRecordSet( loRS ) && Copy data starting from headerrow + 1
Set Safety Off
Delete Database (m.lcTempDb) Deletetables
Select (m.lnSelect)
For ix=1 To Iif( !Empty(m.tcHeaders), ;
ALINES(aHeader, m.tcHeaders,1,','), ;
loRS.Fields.Count )
toRange.Offset(0,m.ix-1).Value = ;
Iif( !Empty(m.tcHeaders), ;
aHeader[m.ix], ;
Proper(loRS.Fields(m.ix-1).Name) )
toRange.Offset(0,m.ix-1).Font.Bold = .T.
Endfor
#Define xlJustify -4130
#Define xlTop -4160
* This part is cosmetic
toRange.WorkSheet.Activate
With toRange.WorkSheet.UsedRange
.VerticalAlignment = xlTop && set all to top
For ix=1 To m.nMemoCount
With .Columns(aMemo[m.ix])
.ColumnWidth = m.tnPrefferredWidthForMemo && 80 chars width
.WrapText = .T.
Endwith
Endfor
.Columns.AutoFit
.Rows.AutoFit
Endwith
Endproc
* Return A, AA, BC etc noation for nth column
Function _GetChar
Lparameters tnColumn && Convert tnvalue to Excel alpha notation
If m.tnColumn = 0
Return ""
Endif
If m.tnColumn <= 26
Return Chr(Asc("A")-1+m.tnColumn)
Else
Return _GetChar(Int(Iif(m.tnColumn % 26 = 0,m.tnColumn - 1, m.tnColumn) / 26)) + ;
_GetChar((m.tnColumn-1)%26+1)
Endif
Endfunc
This is what I was looking for :-) I was trying with my knowledge of Excel Automation programming in Visual FoxPro but always got errors. My task was to create "n" Sheets from one big cursors which I want to parse regarding customer selection of attribute name from cursor to get also "n" Sheets. This sample is for 3 cursors and 3 Sheets and it is generic. But I need this for "n" cursors and one attribute which customer select to distinct and get "n" Sheets in one Excel file. So now I have dynamic procedure. I customized this code and solve my problem which I am trying to end for about 4 days. So again thank you for this code and off course I will not modify VFP2Excel procedure and wrote somewhere else my name. Thanks for help !
There is no native VFP function to do this, BUT, there is an awesome open source project which has a class that will make this very easy:
VFPx Workbook Xlsx - See it here on Github: XLSX Workbook for FoxPro
It has 3 magical functions that will do exactly what you asked for:
CreateWorkbook()
AddSheet()
SaveTableToWorkbook()
(Repeat commands 2 and 3 above for each DBF/Sheet you want to create)
It is well documented with a 54-page PDF and code sample that explains everything you'll need to know.

Barcode in Excel

wondering if someone can help me out with the following problem.
I have staff stock areas with items regularly. As part of the stocking they are required to also charge whatever they send out. The issue is that when they charge they do the repetitive task of data entry for each item they charge out.
In my ideal setup, they can scan a barcode and the task would be completed in seconds since the barcode would contain all the data that needs to be entered.
To automate this, I was thinking of creating one barcode that can capture all the required inputs along with the tab, and enter keys they are required to input And then when the barcode is scanned from a paper print out the info would be automatically charged.
The data driving the barcode is in Excel so I'd like to create the barcode in Excel. This is where I need help, I've tried to add barcode font but it's not working and I have no experience in VBA if that is required.Any guidance would be much appreciated!
You may use barcode generation component to generate barcodes from VBA (as pictures) and insert these pictures into Excel.
Below is the sample code for ByteScout BarCode SDK (commercial component compatible with VBA) sample. Basically, if you want you may replace it with any other component that is capable of creating pictures when called from VBA.
' IMPORTANT: This demo uses VBA so if you have it disabled please temporary enable
' by going to Tools - Macro - Security.. and changing the security mode to ""Medium""
' to Ask if you want enable macro or not. Then close and reopen this Excel document
' You should have evaluation version of the ByteScout SDK installed to get it working - get it from https://bytescout.com
' If you are getting error message like
' "File or assembly named Bytescout SDK, or one of its dependencies, was not found"
' then please try the following:
'
' - Close Excel
' - (for Office 2003 only) download and install this hotfix from Microsoft:
' http://www.microsoft.com/downloads/details.aspx?FamilyId=1B0BFB35-C252-43CC-8A2A-6A64D6AC4670&displaylang=en
'
' and then try again!
'
' If you have any questions please contact us at http://bytescout.com/support/ or at support#bytescout.com
'==============================================
'References used
'=================
'Bytescout Barcode SDK
'
' IMPORTANT:
' ==============================================================
'1) Add the ActiveX reference in Tools -> References
'2) Loop through the values from the Column A for which barcode has to be generated
'3) Parse the value to Bytescout Barcode Object to generate the barcode using QR Code barcode type.
'4) Save the generated Barcode Image
'5) Insert the Barcode Image in the Column B
'6) Repeat the steps 3 to 5 till the last Value in Column A
'
'==================================================================
Option Explicit
' declare function to get temporary folder (where we could save barcode images temporary)
Declare Function GetTempPath _
Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, _
ByVal lpBuffer As String) As Long
' function to return path to temporary folder
Public Function fncGetTempPath() As String
Dim PathLen As Long
Dim WinTempDir As String
Dim BufferLength As Long
BufferLength = 260
WinTempDir = Space(BufferLength)
PathLen = GetTempPath(BufferLength, WinTempDir)
If Not PathLen = 0 Then
fncGetTempPath = Left(WinTempDir, PathLen)
Else
fncGetTempPath = CurDir()
End If
End Function
Sub Barcode_Click()
'Fetch the Worksheet
Dim mySheet As Worksheet
Set mySheet = Worksheets(1) 'Barcode_Data Sheet
'temp path to save the Barcode images
Dim filePath As String
filePath = fncGetTempPath() 'Change the Path But should end with Backslash( \ )
'Prepare the Bytescout Barcode Object
'====================================
Dim myBarcode As New Bytescout_BarCode.Barcode
myBarcode.RegistrationName = "demo" 'Change the name for full version
myBarcode.RegistrationKey = "demo" 'Change the key for full version
'Barcode Settings
myBarcode.Symbology = SymbologyType_QRCode ' QR Code barcode, you may change to other barcode types like Code 39, Code 128 etc
' set barcode image quality resolution
myBarcode.ResolutionX = 300 'Resolution higher than 250 is good for printing
myBarcode.ResolutionY = 300 'Resolution higher than 250 is good for printing
myBarcode.DrawCaption = True 'Showing Barcode Captions in the Barcode Image
myBarcode.DrawCaptionFor2DBarcodes = True ' show captions for 2D barcodes like QR Code
' first clean the B column from old images (if any)
Dim Sh As Shape
With mySheet
For Each Sh In .Shapes
If Not Application.Intersect(Sh.TopLeftCell, .Range("B1:B50")) Is Nothing Then
If Sh.Type = msoPicture Then Sh.Delete
End If
Next Sh
End With
' now generate new barcodes and insert into cells in the column B
' Repeat the steps for each row from 2 to 6
Dim myVal As Integer
For myVal = 2 To 6 'change the code to all rows with values
'Parse the Value from the Column A to Bytescout Barcode Object
myBarcode.Value = mySheet.Cells(myVal, 1).Text
'Fit the barcode into 80X30 mm rectangle
myBarcode.FitInto_3 80, 30, 4 '4 refers to units of measurement as millimeter
'Save the barcode image to a file in temporary folder
myBarcode.SaveImage filePath & "myBarcode" & myVal & ".png"
'Insert the Barcode image to the Column B and resize them to fit the cell.
'==========================================================================
With mySheet.Pictures.Insert(filePath & "myBarcode" & myVal & ".png")
.ShapeRange.LockAspectRatio = True ' lock aspect ratio
.Left = mySheet.Cells(myVal, 2).Left + 1 ' set left
.Top = mySheet.Cells(myVal, 2).Top + 1 ' set right
.PrintObject = True ' allow printing this object
.Placement = xlMove ' set placement mode to move but do not resize with the cell
.ShapeRange.ScaleHeight 1, True ' set height scale to 1 (no scale)
.ShapeRange.ScaleWidth 1, True ' set width scale to 1 (no scale)
End With
Next myVal ' move to next cell in the column
' Release the Barcode Object.
Set myBarcode = Nothing
End Sub
Disclaimer: I'm relatd to ByteScout

How to save ole object (contains jpg,excel, pdf file)to file in powerbuilder

I have saved data in format of blob using powerbuilder ole control in oracle.
Now we want to convert these blob to files,
files are of different format(PDF, JPG,EXCEL,TEXT,DOC)
There are more than 1 Million files so it is not easy to do manually open and save using olecontrol.
Can we do it through script auto saving of blob to file in powerbuilder
Yes, it is possible:
Write a cursor in PowerBuilder embedded SQL to get for each record in your blob table the key and the and file extension (if you have those). The syntax for that kind of thing looks like this:
Long ll_Key
String ls_Ext
DECLARE GetBlobCursor CURSOR FOR
SELECT blob_key,
blob_extension
FROM blob_table ;
/* need to loop here while SQLCA.SQLCode is good */
FETCH GetBlobCursor
INTO :ll_Key,
:ls_Ext ;
Use a SELECTBLOB embedded SQL statement to get the blob data into a PowerBuilder BLOB variable:
Blob lblob_File
SELECTBLOB fileblob
INTO :lblob_File
FROM blobtable
WHERE blob_key = :ll_Key ;
Use FileOpen and FileWrite to write the blob with a valid file name and extension:
Long ll_Loops, ll_Step
Int li_File
String ls_Path
ls_Path = "<where do you want me?>." + String(ll_Key) + "." + ls_Ext
li_File = FileOpen(ls_Path, StreamMode!, Write!, LockWrite!, Append!)
If li_File > 0 Then
// Determine how many times to call FileWrite
ll_FileLen = Len(lblob_File)
If ll_FileLen > 32765 Then
If Mod(ll_FileLen, 32765) = 0 Then
ll_Loops = ll_FileLen/32765
Else
ll_Loops = (ll_FileLen/32765) + 1
End If
Else
ll_Loops = 1
End If
For ll_Step = 1 To ll_Loops
FileWrite(li_File,BlobMid(lblob_File,((ll_Step - 1)*32765) + 1, 32765))
Next
Else
//log the error, or handle
End If
FileClose(li_File)
Hope that gets you started.

Resources