Skip to content

Instantly share code, notes, and snippets.

@Yonaba
Created June 29, 2011 14:09
Show Gist options
  • Save Yonaba/1053902 to your computer and use it in GitHub Desktop.
Save Yonaba/1053902 to your computer and use it in GitHub Desktop.
Simply Convert Text File To PDF Using LuaHPDF
--LUA Txt to PDF Converter
--Thanks to Takeshi Kanno (HaruFreePDF Lib) and LUAHPDF Module
--We load the library
require 'hpdf'
--Assuming filename 'input.txt'
local filename = 'input.txt'
--We seek the file to collect data inside a table
local file = assert(io.open(filename,'r'))
local data = {}
if file then
for line in file:lines() do table.insert(data,line) end
file:close()
else
error('Cannot open file test.txt')
end
print(#data..' lines found!')
--Assuming each page will make 40 lines maximum, we split the data table
--in different pages..Each page is store in a single table, and all
--pages are hold in a table named stream.
local stream = {}
if #data > 40 then
local count = 0
repeat
count = count+1
stream[count]={}
for i=40*(count-1)+1,40*(count) do
if data[i] then
table.insert(stream[count],data[i])
end
end
until 40*count>#data
else
stream[1]=data
end
print('The output Pdf file will make '..#stream..' pages!')
--We create a New Pdf Object
local newPdf = hpdf.New()
if newPdf then
--We go through all pages in stream tables
for i in ipairs(stream) do
--for each page in stream, we create a new Page, and set the font & size
local page = hpdf.AddPage(newPdf)
local font = hpdf.GetFont(newPdf,"Helvetica")
hpdf.Page_SetFontAndSize(page,font,12)
hpdf.Page_BeginText(page)
--We write the current page contents
local y=hpdf.Page_GetHeight(page)
local depler = 60
for _ in ipairs(stream[i]) do
hpdf.Page_TextOut(page,20,y-depler,stream[i][_])
depler = depler+14
end
hpdf.Page_EndText(page)
end
--We save the pdf Object and frees it from memory
hpdf.SaveToFile(newPdf,'test.pdf')
hpdf.Free(newPdf)
else
error('Error While creating PDF File')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment