pdf conversion in c# : How to save filled out pdf form in reader application SDK tool html .net asp.net online itext_so-sample7-part1258

ExtractingtextfromPDFs
65
RenderFilter[] filter = {new RegionTextRenderFilter(rect)};
ITextExtractionStrategy strategy;
StringBuilder sb = new StringBuilder();
for (int i = 1; i i <= = reader.NumberOfPages; ; i++) {
strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy\
(), filter);
sb.AppendLine(PdfTextExtractor.GetTextFromPage(reader, i, strategy));
}
Nowyou’llgetallthetextsnippetsthatintersectwiththe
rect
(sopartofthetextmaybeoutside
rect
,iTextdoesn’tcuttextsnippetsinpieces).
NotethatyoucangettheMediaBoxofapageusing:
Rectangle mediabox = reader.GetPageSize(pagenum);
The coordinate of the lower-left corner is x =
mediabox.Left
and y =
mediabox.Bottom
; the
coordinateoftheupper-rightcornerisx=
mediabox.Right
andy=
mediabox.Top
.
Thevaluesofxincreasefromlefttoright;thevaluesofyincreasefrombottomtotop.Theunitof
themeasurementsysteminPDFiscalled“userunit”.Bydefaultoneuserunitcoincideswithone
point(thiscanchange,butyouwon’tfindmanyPDFswithadifferentUserUnitvalue).Innormal
circumstances,72userunits=1inch.
How to save filled out pdf form in reader - extract form data from PDF in C#.net, ASP.NET, MVC, Ajax, WPF
Help to Read and Extract Field Data from PDF with a Convenient C# Solution
extract table data from pdf; pdf form field recognition
How to save filled out pdf form in reader - VB.NET PDF Form Data Read library: extract form data from PDF in vb.net, ASP.NET, MVC, Ajax, WPF
Convenient VB.NET Solution to Read and Extract Field Data from PDF
pdf form data extraction; extracting data from pdf forms to excel
General questions about iText
ThesearesomequestionsaboutiTextingeneral.Theyaren’talwaysaboutatechnicalproblem,but
theycanbeaboutabasicconceptthatisexplainedinmoredetailinoneofthelaterchapters.
Unit Testing and Automated Testing Questions
IhavebeensearchingforsomeunittestsfortheprogramiTextwith noluck.Isanyone
awareof any suchtests?Also, doesanyone know if the developersuse any automatic
testingtoolsoniText,suchasJenkins?
PostedonStackOverflowonFeb21,2014¹¹⁵byuser3338813¹¹⁶
Internally,weuseJenkinsaswellasTeamCity.
Wehavetwotypesoftests:
1. The tests thatareaddedwhen new core functionality is added. You can find thesewhere
Mavenexpectsthem:eachMavenprojecthasa
src
directorywith2subdirectories:
main
and
test
.Forinstance:ifyoulookatiTextcore,you’llfindthereleasedstuffhere¹¹⁷andthetests
here¹¹⁸.Mostofthesetestsarebuiltontopofour testutils¹¹⁹.
2. TheteststhatareaddedwhenwegetquestionsonSOorwhenwecreatecodesamplesfor
thebooks. For theseweusea generic testclassessuch asGenericTest¹²⁰andSandboxSam-
pleWrapper¹²¹.Thewrapperclassmakescreatingatestano-brainer.Allyouneedtodoto
turnasampleinto atestisaddingthe
@WrapToTest
annotation.Well,actuallythere’smore
involved:youneedtofollowaspecificpatternwhenwritingasample:alwaysuse
SRC
and
DEST
for source PDFs andresulting PDFs, alwaysuse a
createPdf()
or
manipulatePdf()
method,andalwaysgivethecmpfilethesamenameasthe
DEST
fileprefixedwith
cmp_
.
Inbothcases,you’llfindPDFfilesofwhichthenamestartswith
cmp_
,seeforinstancethecmpfiles
folder¹²²fortheexamples.Inbothcases,you’llfindreferencestoGhostscriptandacomparetool
(you’llneedtoconfigurethese).
¹¹⁵
http://stackoverflow.com/questions/21944424/itext-unit-testing-and-automated-testing-questions
¹¹⁶
http://stackoverflow.com/users/3338813/user3338813
¹¹⁷
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/itext/src/main/
¹¹⁸
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/itext/src/test/
¹¹⁹
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/itext/src/main/java/com/itextpdf/testutils/
¹²⁰
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/sandbox/src/test/java/sandbox/GenericTest.java
¹²¹
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/sandbox/src/test/java/sandbox/SandboxSampleWrapper.java
¹²²
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/sandbox/cmpfiles/
VB.NET Image: How to Draw and Cutomize Text Annotation on Image
can adopt these APIs to work out more advanced Fill.Solid_Color = Color.Gray 'set filled shapes color As Bitmap = obj.CreateAnnotation() img.Save(folderName &
pdf form save in reader; filling out pdf forms with reader
VB.NET TIFF: Make Custom Annotations on TIFF Image File in VB.NET
This online guide content is Out Dated! with image, as well as delete and save annotation made set annotation edge color 'set the property of filled shape obj
extract data from pdf c#; pdf data extractor
GeneralquestionsaboutiText
67
Why do I get a “Could not find
PdfGraphics2D
”error?
I have
come
across
a
runtime
exception
“Could
not find
class
com.itextpdf.awt.PdfGraphics2D
”. I wanted tocreate a PDFdocument from android
device.ForthatIusediTextlibrary.ThismycodeforcreatingPDF:
Document document new Document();
PdfWriter.getInstance(document, outStream);
document.open();
document.add(new Paragraph(data));
document.close();
Thecodeworksfine.ItiscreatingPDFsuccessfully.butitgivesmearuntimeexception:
06-14 10:09:20.491: W/dalvikvm(764):
Unable to resolve superclass of Lcom/itextpdf/awt/PdfGraphics2D; (1251)
06-14 10:09:20.491: W/dalvikvm(764):
Link of class 'Lcom/itextpdf/awt/PdfGraphics2D;' failed
06-14 10:09:20.491: E/dalvikvm(764):
Could not find class 'com.itextpdf.awt.PdfGraphics2D',
referenced from method com.itextpdf.text.pdf.PdfContentByte.createGraphics
06-14 10:09:20.491: W/dalvikvm(764):
VFY: unable to resolve new-instance 480
(Lcom/itextpdf/awt/PdfGraphics2D;) in Lcom/itextpdf/text/pdf/PdfContentByte;
06-14 10:09:25.280: E/dalvikvm(764):
Could not find class 'org.bouncycastle.cert.X509CertificateHolder',
referenced from method com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj
06-14 10:09:25.280:
W/dalvikvm(764): VFY: unable to resolve new-instance 1612
(Lorg/bouncycastle/cert/X509CertificateHolder;) in Lcom/itextpdf/text/pdf/Pd\
fReader;
Ihavedonecleanand build,addedjar tolibsfolderandmakeitselected onorderand
exportandidonelotofresearchforpast2days.butnothinghelpedme.Baseduponmy
knowledgethereshould bethesepossibilities: (1) theexternaljarisn’tloadedproperly,
or(2) theclass
PdfGraphics2D
extends
java.awt.Graphics2D
whichisnotavailable on
Android.
PostedonStackOverflowonJun14,2013¹²³byR9J¹²⁴
¹²³
http://stackoverflow.com/questions/17102533/could-not-find-class-com-itextpdf-awt-pdfgraphics2d
¹²⁴
http://stackoverflow.com/users/1912085/r9j
VB.NET PDF: Use VB Code to Draw Text and Graphics on PDF Pages for
This online guide content is Out Dated! obj.FontBrush.Solid_Color = Color.Blue 'set filled font color As Bitmap = obj.PDFTextDrawing() img.Save(folderName__1 &
save pdf forms in reader; pdf data extraction open source
C#: XDoc.HTML5 Viewer for .NET Online Help Manual
4. FilledRectangle. Click to draw a filled rectangle annotation. Click to save created redaction with customized name. 6. zoomIn. Click to zoom out current file.
extract data from pdf form fields; exporting pdf data to excel
GeneralquestionsaboutiText
68
You’vediscoveredthat
PdfGraphics2D
extends
java.awt.Graphics2
D, andasyoualready know
Graphics2D
isaforbiddenclassonAndroid.
You’vealsoencounteredproblemsrelatedtoBouncyCastle.
This tells me that you’re using the Java version of iText instead of theAndroidport¹²⁵. In the
Androidport,wereplacedBouncyCastlebySpongyCastle(asrecommendedwhenusingencryption
onAndroid) andweremovedallreferencesto forbiddenclasses(for instanceinthe
awt
and
nio
packages).
PleaseswitchtousingtheAndroidportofiText.ItiscallediTextG¹²⁶.
Why do I get a “
getOutputStream()
has already been
called for this response” error in JSP?
I’musingJDBCtofetchdatafromdatabaseandthenIuseiTexttocreateaPDFfilewhich
canbedownloadedonclientmachine.TheapplicationiscodedinHTML/JSPandrunson
ApacheTomcat.
Iusethe
response.getOutputStream
tocreateanoutputPDFfileimmediately.However,
Igetthefollowingerror:
getOutputStream()
hasalreadybeencalledforthisresponse
HowcanIgenerateadynamicPDFfilewhichcanbedownloadedbyclientmachine?
PostedonStackOverflowonJun13,2013¹²⁷bySahilSharma¹²⁸
WhenyouwriteJSP,youprobablylikewhitespaceandindentation,forinstance:
¹²⁵
http://itextpdf.com/product/itextg
¹²⁶
http://itextpdf.com/product/itextg
¹²⁷
http://stackoverflow.com/questions/17083318/how-to-insert-image-in-pdf-using-itext-and-download-to-client-machine
¹²⁸
http://stackoverflow.com/users/2367475/sahil-sharma
C# Image: C#.NET Code to Add Rectangle Annotation to Images &
Add-on successfully stands itself out from other C# Color.Gray;//set filled shape color img = obj.CreateAnnotation(); img.Save(folderName + "RectangleAnnotation
pdf data extraction to excel; export pdf data to excel
GeneralquestionsaboutiText
69
<% //a line of code %>
<%
// some more code
%>
<% // another line of code %>
<%
response.getOutputStream();
%>
Thiswillalwayscausetheexception
"getOutputStream() has already been called for this
response"
regardlessifyou’reusing iTextornot.The
getOutputStream()
methodwascalledthe
momentyouintroducedyourfirstwhitespacecharacterinyourJSPscript.
Tofixthis,youneedtoremoveallwhitespace:
<% //a line of code %><%
// some more code
%><% // another line of f code %><%
response.getOutputStream();
%>
Nota singlecharacter is accepted outsidethe
<%
and
%>
markers. Asexplained in thebetter JSP
manuals,youshouldn’tuseJSPtocreatebinaryfiles.Whynot?BecauseJSPintroduceswhitespace
charactersatarbitraryplacesinyourbinaryfile.Thatresultsincorruptfiles.UseServletsinstead!
Legal questions
Although StackOverflow is a forum where developers post technical questions and technical
questionsonly,wenoticethatsomedevelopersalsowanttoknowmoreaboutthelegalaspectsof
usingopensource,morespecifically:isitlegaltouseiTextforfree?Istherealicensefeeinvolved?
What is the difference between Lowagie and iText?
What is thedifferencebetween lowagieandiText.Is thisjustversiondifferenceorup-
gradationtolibrary.Whichonerecommendedtobeused.
PostedonStackOverflowonNov22,2012¹²⁹byAdeebCheulkar¹³⁰
IamLowagie,thelowagieyoureferto.I’mtheoriginalauthorofiTextandtheauthorofthe“iText
inAction”books.
AsexplainedintheSalesFAQ¹³¹,youshouldusethelatestversionofiText.
ThedifferencesbetweenoldversionsofiText(iText2.x.ydatesfromJuly2009orearlier)andnewer
versionsofiTextcanbefoundinthechangelogs¹³².
The5.0.0versionhadthefollowingsubstantialchanges:
• iTextandiTextSharpstartedusingthesameversionnumbers
• theiText.jariscompiledusingJava5(insteadofwiththeJDK1.4).
• TheF/OSSlicensehasbeenupgradedfromMPL/LGPLtoAGPL.
• Thepackagenameshavechangedfrom
com.lowagie
to
com.itextpdf
.
• The toolbox and RTF support have been removed: they are now in a separate project at
SourceForge.
NumerousbugshavebeenfixedsinceJuly2009.Functionalitythatmakesyour PDFsfuture-proof
such as updatesregarding new digital signaturestandards and new standards such asPDF/UA,
PDF/A-2andPDF/A-3isonlyavailableinthemorerecentiTextversions.
¹²⁹
http://stackoverflow.com/questions/13515210/difference-between-lowagie-and-itext
¹³⁰
http://stackoverflow.com/users/1771109/adeeb-cheulkar
¹³¹
http://itextpdf.com/salesfaq
¹³²
http://itextpdf.com/changelog
Legalquestions
71
Can iText 2.1.7 or earlier be used commercially?
CaniText2.1.7(MPL/GPL)licencebeusedincommercialprojects?Iamnotalegalguybut
lotsofdiscussionthreadssuggestthatthereisnoissueusingtheearlierversion(2.1.7)of
iTextincommercialprojectsasthatversionisboundedwithterms&conditionsgoverned
byMPL¹³³/GPLlicense.
However,ifwelookatiText’sofficialwebsite¹³⁴,itsaysasthelicencehasbeenupgraded
toAGPLlicence,onehastobuythesoftwarebeforecommerciallyusingit.Seethetopic
entitledWhyshouldn’tIuseiText2.x(oriTextSharp4.x)?
LEGAL REASONS:OlderversionsofiTextunderthefreemodelmaycon-
tain code fragments thatinfringeotherpeople’scopyrightsorintellectual
propertyrights.iTextSoftwareGrouphasdoneasignificantinvestmentin
identifyingandeliminatingallthosecasesasofversion5.1.whichisoneof
thereasonwhyitisnowapayingcommercialversion.Wedonotrecommend
theuseofversionspriorto5.1forcommercialprojectsasyourcompanycould
beliableforcopyrightorIPinfringements.
Of course, this seems a warning only. Discouragement of not using iText with earlier
version duetoTechnicalreasons could beunderstoodbutLegalreasonsarenotworth.
WhataboutthecommercialprojectswhohavebeenusingiText2.1.7beforethelicence
upgradehappenediniText?Wouldtheynowhavetochangetheirwholeprojectplanning
because iTexthasnow change hismindtonot todistributeitcommercially?Ofcourse
iTextmighthasdonesignificantinvestmentinupgradingtheversiontechnicallybutwhat
abouttheinvestmentonemighthavedoneinhiscommercialprojectusingiText2.1.7or
earlier?
Please someone who understands legal implications of both the licences clarify this
confusion.iTextcanusesuchwarningtoencourageitssalebutisthereanythingsubstantial
insuchwarning?CanoneuseiTextwithversion2.1.7orearliercommercially?Comments
fromMr.BrunoLowagie,theoriginalauthorofiTextarehighlyappreciated.
PostedonStackOverflowonSep6,2014¹³⁵byDevendraSharma¹³⁶
The first iText company was founded in 2008. The purpose of thiscompany wasto put all the
IntellectualPropertyofthecodeintoonelegalentity.Thiswasachievedbyidentifying [1.]every
thirdpartyprojectfromwhichcodewasborrowed,aswellas[2.]everyindividualdeveloperwho
contributedcode.
¹³³
https://www.mozilla.org/MPL/1.1/
¹³⁴
http://itextpdf.com/salesfaq
¹³⁵
http://stackoverflow.com/questions/25696851/can-itext-2-1-7-or-earlier-can-be-used-commercially
¹³⁶
http://stackoverflow.com/users/2881228/devendra-sharma
Legalquestions
72
[1.]Somecodesnippetswereborrowedfromprojectswithanambiguouslicense.Forinstance:we
hadasnippetthatwasreleasedunderSun’sExampleLicense(whichallowedustousethecode),but
inthecommentsectionoftheclass,itsaidthatthecodewasproprietarytoSUN(whichprevented
ustousethecode). Whichofbothprevailed?Being anignorantdeveloperatthattime,I thought
theExampleLicensewastheoneIcoulduse,justlikesomepeopleclaimthatyoucanuseiText2.1.7
today.Lawyershowever,disagreed:theysaidthatthemoststrictlicensewasthevalidone.
We solved these problems by (1) asking permission to use code with ambiguous licenses, (2)
refactoringcodeifwedidn’tgetpermission,(3)removingcodewecouldn’trefactor.
Wedidthesamewithcontributionsfromindividualdevelopers.
[2.]TheIPfromindividualdeveloperswastransferredtoiTextGroupNV(formerlyknownas1T3XT
BVBA)byaskingeverydeveloper whocontributed20linesofcodeormoreto signaContributor
LicenseAgreement.
Twoproblemsarose:
1. Individual developers could not be reached. For example: we dropped the RTF package
completelybecausewecouldn’tfindacoupleofthecoredevelopersoftheRTFfunctionality.
2. Inacoupleofcases,wehadtonegotiateabouttheCLA. For example: onecompanydidn’t
liketheCLA.Instead,thiscompanyreleasedthecontributionofitsemployeesunderanMIT
license,sothatwecoulduseitanyway.Anotherorganizationwasreallyslowinagreeingwith
theCLA.IttookusuntilSeptember2009beforewereceivedformalapproval.Onlyafterthis
approval,weswitchedto theAGPL.Ican’tdisclosethedocument(itwasdifferentfromthe
CLA),northenameoftheorganization(IhopeIdon’tbreaktheNDAjustbywritingthis).I
canonlysaythatweonlyhadfullcoverageofthecodebaseafterthatdocumentwassigned.
IgnorantdevelopersclaimthattheLGPL/MPLheader“protects”them,butwhatifsomeproprietary
codewasaccidentallyaddedto aclasswithsuchaheader?Doesthismakethatproprietarycode
“availableunder theMPL/LGPL”? Ifitdid,itwouldbesufficientto takeproprietarycode,addan
MPL/LGPLheaderandpublishit.Doingthisonpurposewouldbeillegal.Doingthisoutofignorance
canbepardonedifthereisawillingnesstofixtheissue.
Intheearlyyearsofopensource,itdidoccurthatproprietarycodegotmixedintoanopensource
projectbyaccident. AtiText, wehaveinvestedalotoftimeandeffortinto cleaningupthecode
base.Sincethatexercise,weareverydisciplinedwithrespecttocodecontributions.Thisisoneof
thecoretasksofaprofessionalopensourcecompany.
Afterwefixedalltheissues,weremovedallcopiesofthoseoldiTextversionsfromourserversto
makesurewewereintheclear.IfacompanydecidestousesomerogueversionofiText2.1.7thatis
outsideofourcontrol,thiscompanydoessowillinglyandknowingly,inotherwords:atitsown
risk!Thereisnowaysuchacompanycanclaim:“Wedidn’tknowtherewasapossibleIPissuewith
thecode.”
Ifyou want to use iText2.1.7, you need to do the exercisewe havedone between 2007-2009 at
yourownexpense.Thiswillcostyoumorethanthepriceofalicense.Forinstance:theindividual
Legalquestions
73
developersgavepermissionto iTextGroupNVto do businesswith iText, butwill they givethat
permissiontoyou?Howwillyouidentifythoseindividualdevelopers?
Moreover:iText2.1.7datesfromJuly2009,meaningthatitismorethan5yearsold.Manybugshave
beenfixedsincethatdate.Shouldyouknowinglyintroducethosebugsintothecodebaseofyour
customer,thenyourcustomermayclaimthatyouhadanalternative:youcouldhaveusedamore
recentversionofiText…
Asforyourquestion“whatabouttheinvestmentonemighthavedoneinhiscommercialprojectusing
iText2.1.7orearlier?”Thatinvestmentmusthavebeendoneatleast3yearsago,becausewe’vebeen
informingpeoplethattheyshouldupgradeforatleastthatlong.Upgradingtoarecentversionisan
investmentthatshouldbecategorizedasamaintenancecost.Itshouldbeanaffordablecostbecause
whoeverhasbeenusing iText2.1.7forthatlong inacommercialprojecthasbeenmakingmoney
thankstoiTextforthatlong.Claimingthat“iTexthasnowchangeditsmind”isnotcorrectunless
nowismarkedasasynonymof5yearsagoinyourdictionary.
To be continued…
AlltheanswersandthemanycodesamplesIhaveprovidedonStackOverflowwerewritteninthe
hopethattheyarehelpful. Ileaveituptothereaderofthis“Bestof”selectionto decidewhether
ornot“I’mkindofa dick” asthepeoplewhodown-votedsomeofmyanswersclaim.I justlove
answeringquestions,andwhereloveisinvolved,there’salsopain,forinstancethepainifthelove
isn’treturned.Somepeopleseemtomakeasportoutofittobegforananswerandthentothankme
bysaying:we’renevergoingtobeacustomerofiTextSoftware.Somehowthatdoesn’tcompute.I
hopeyouunderstand.
Obviously,abooklikethisisneverfinished.NewquestionsaboutiTextarepostedeveryday.Iexpect
thatthisbookwillgrowovertheyears.Someanswersmaybecomeobsolete,somenewfunctionality
willrequiremoreclarification.Thisclarificationmaybeprovidedintheformofananswertoanew
question,orasatopicinoneoftheotherupcomingbooks:
• TheABCofPDF¹³⁷
• CreateyourPDFswithiText¹³⁸
• UpdateyourPDFswithiText¹³⁹
• SignyourPDFswithiText¹⁴⁰
Allofthesebooksareavailableforfree.Nodonationisexpected.
¹³⁷
https://leanpub.com/itext_pdfabce
¹³⁸
https://leanpub.com/itext_pdfcreate
¹³⁹
https://leanpub.com/itext_pdfupdate
¹⁴⁰
https://leanpub.com/itext_pdfsign
Documents you may be interested
Documents you may be interested