FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin para Harbour/xHarbour obtener un pdf via API ( SOLUCIONADO )
Posts: 1074
Joined: Fri Oct 07, 2005 01:56 PM
obtener un pdf via API ( SOLUCIONADO )
Posted: Wed Apr 16, 2025 01:37 AM
hola a tod@s

Estimados estoy obteniendo un pdf via api, pero me responde en un formato text
necesito convertirlo a pdf pero si lo graba directo como pdf me sale error en el archivo

alguna forma de poder grabarlo a pdf

se agradece cualquier ayuda

adjunto parte del archivo que devuelve
algo asi
%PDF-1.7
%����
1 0 obj
<<
/Type /Catalog
/Pages 4 0 R
/MarkInfo<</Marked true>>
/Metadata 22 0 R
/OutputIntents 24 0 R
/StructTreeRoot 5 0 R
/PageMode /UseNone
/OCProperties << /OCGs [6 0 R] /D << /ON [6 0 R] /AS [<</Event /Print /OCGs [6 0 R] /Category [/Print]>>] >> >>
>>
endobj
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM
Re: obtener un pdf via API
Posted: Wed Apr 16, 2025 04:51 AM
Hola, no sé como haces el request para obtener el fichero
Todo indica que en tu request no está definido correctamente el "Content-Type:", que es el que indica lo que se espera del request
https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Type
Si no te aclaras y me das un poco más de informacion respecto a como haces el request podré ayudarte mejor
Cristobal Navarro

Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo

El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
Posts: 8515
Joined: Tue Dec 20, 2005 07:36 PM
Re: obtener un pdf via API
Posted: Wed Apr 16, 2025 03:13 PM
¿Te refieres a algo así?

https://www.fpdf.org/?go=script&id=75

Sinceramente no entendí tu pregunta.

Regards, saludos.
João Santos - São Paulo - Brasil - Phone: +55(11)95150-7341
Posts: 231
Joined: Fri Jul 20, 2012 01:49 AM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 12:45 AM
Me parece ser lo raw del PDF

Prueba con:

cBuffer es lo que te devolve
hb_memoWrit( "file.pdf", cBuffer )
Patricio Avalos Aguirre wrote: hola a tod@s

Estimados estoy obteniendo un pdf via api, pero me responde en un formato text
necesito convertirlo a pdf pero si lo graba directo como pdf me sale error en el archivo

alguna forma de poder grabarlo a pdf

se agradece cualquier ayuda

adjunto parte del archivo que devuelve
algo asi
%PDF-1.7
%����
1 0 obj
<<
/Type /Catalog
/Pages 4 0 R
/MarkInfo<</Marked true>>
/Metadata 22 0 R
/OutputIntents 24 0 R
/StructTreeRoot 5 0 R
/PageMode /UseNone
/OCProperties << /OCGs [6 0 R] /D << /ON [6 0 R] /AS [<</Event /Print /OCGs [6 0 R] /Category [/Print]>>] >> >>
>>
endobj
Regards,

Lailton Fernando Mariano
Posts: 1074
Joined: Fri Oct 07, 2005 01:56 PM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 01:17 PM
gracias por las respuestas

layton al procesar me genera hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseText )y abrir el pdf error al procesar página. colorSpace no válido

cnavarro, el api tambien tiene en su web para ir probando y me da lo mismo
https://docs.skualo.cl/reference/obtener-pdf-documento

https://ibb.co/kVSbgSgB



gracias por su ayuda :-)
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
Posts: 231
Joined: Fri Jul 20, 2012 01:49 AM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 05:56 PM
para PDF te recommendo usar asi:
hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseBody )
se no funcionar, prueba com asi:
hb_memoWrit( "c:\paso\file.pdf", hb_strToUtf8( oHttp:ResponseBody ) )
:)
Regards,

Lailton Fernando Mariano
Posts: 1074
Joined: Fri Oct 07, 2005 01:56 PM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 05:58 PM
ahh se me fue la empresa me envio esta respuesta

Te recomiendo hacer la prueba desde Postman, ya que lo que devuelve la api en ese endpoint es el archivo PDF como tal.

:mrgreen:
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
Posts: 1074
Joined: Fri Oct 07, 2005 01:56 PM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 06:14 PM
por postman funciona bien el pdf :-(

Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
Posts: 1344
Joined: Wed Nov 16, 2005 09:14 PM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 07:29 PM
Patricio:
Pareciera que esta todo bien y lo que te devuelve es el pdf correcto.
Como grabas luego de obtener el texto?
Con lo que te comenta Lailton creo que deberia funcionar bien
  hb_memowrit('mipdf.pdf',oHttp:ResponseBody)
   shellexecute(0,"open",hb_curdrive()+":\"+CurDir()+"\mipdf.pdf",,,1)
Posts: 231
Joined: Fri Jul 20, 2012 01:49 AM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 08:35 PM
tiene probado asi?
Lailton wrote: para PDF te recommendo usar asi:
hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseBody )
se no funcionar, prueba com asi:
hb_memoWrit( "c:\paso\file.pdf", hb_strToUtf8( oHttp:ResponseBody ) )
:)
Regards,

Lailton Fernando Mariano
Posts: 1074
Joined: Fri Oct 07, 2005 01:56 PM
Re: obtener un pdf via API
Posted: Thu Apr 17, 2025 09:35 PM
Gracias !!!!
Laiton funcionooo
hb_memoWrit( "c:\paso\file.pdf", oHttp:ResponseBody )
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
Posts: 231
Joined: Fri Jul 20, 2012 01:49 AM
Re: obtener un pdf via API ( SOLUCIONADO )
Posted: Fri Apr 18, 2025 02:02 AM
8)
Regards,

Lailton Fernando Mariano
Posts: 336
Joined: Wed May 16, 2007 09:40 PM
Re: obtener un pdf via API ( SOLUCIONADO )
Posted: Wed Apr 30, 2025 04:26 PM
Hola Patricio

Podrias colocar parte del programa donde envias la consulta y la respuesta, yo estoy en lo mismo pero no logro construir el PDF

Este es mi programa, te agradeceria tu ayuda

FUNCTION RDOCLPT(TS_TOKEN)
LOCAL oHttp,Doc,cxmLbody,oIni,nHandle
LOCAL ts_exit:=.t.,tw_servidor:='',ts_mj1:='',ts_modulo:=.f.
LOCAL ts_servidor:="https://sveqa.zofri.cl/sveProcDocWSN/Emision?WSDL"

if empty(ts_token)
msginfo('Debe Obtener un Token de Inicio para Autentificarse en Web Service','Token de Sesion')
return .f.
endif

cXmlBody:= '' +;
'<?xml version="1.0" encoding="utf-8"?>' + ;
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cl="cl.zofri.sve" xmlns:wsn="http://cl/zofri/sve/prd/wsn">'+;
' <soapenv:Header>'+;
' <cl:token>'+ts_token+'</cl:token>'+;
' </soapenv:Header>'+;
' <soapenv:Body>'+;
' <wsn:emisionDocumento>'+;
' <wsn:codigoAduaneroDoc>101-25-051206</wsn:codigoAduaneroDoc>'+;
' <wsn:tipoEmision>E</wsn:tipoEmision>'+;
' </wsn:emisionDocumento>'+;
' </soapenv:Body>'+;
'</soapenv:Envelope>'

TRY
oHttp := CreateObject( 'MSXML2.XMLHTTP.6.0' )
CATCH
oHttp := CreateObject( 'Microsoft.XMLHTTP' )
END
doc = CreateObject("MSXML2.DOMDocument.6.0")

oHttp:Open( "POST" , ts_servidor, .F. )
ohttp:SetRequestHeader( "Content-Type" , "text/xml; charset=utf-8" )
oHttp:SetRequestHeader( "Connection:", "Keep-Alive" )
doc:LoadXML( cXmlbody )

TRY
ohttp:Send( doc:xml )
CATCH
cErrorMsg:='No Se Pudo Enviar Documento XML...'+CRLF+CRLF+;
'Sin Conexion a Internet o Servidor Con Problemas'
msginfo(cErrorMsg,"Intente Nuevamente")
return .t.
END
// ?ohttp:status
//status 200 = OK
// 500 = ERROR

response = ohttp:responsetext

hb_memoWrit( "fileout.pdf", oHttp:ResponseBody )

//crear un archivo para leer tag
cFilename:="texto.xml"
MEMOWRIT( cfilename, response, .F. )
//leer archivo para extraer el factura pdf
CTXT:=MEMOREAD(CFILENAME)
pdfin:=at("%PDF-1.4",CTXT)
pdfend:=At("%EOF",CTXT)
largo:=pdfend-pdfin
Cresp:=substr(CTXT,pdfin,largo+4)

//SE CREA EL ARCHIVO PDF
CPDF:="TEXTO.PDF"
MEMOWRIT( cPdf, CRESP, .F. )

RETURN .T.
Fivewin-Xharbour 24.09, Iquique, Chile
Posts: 1074
Joined: Fri Oct 07, 2005 01:56 PM
Re: obtener un pdf via API ( SOLUCIONADO )
Posted: Sun May 04, 2025 03:50 PM
Hola adjunto lo solicitado
cUrlSkualo := 'https://api.skualo.cl/'+_TOKENEMP_+'/documentos/'+cId+'/pdf'  //esta info es entregado por el api 

oDoc := CreateObject( "MSXML2.DOMDocument" )
oHttp := CreateObject( "MSXML2.XMLHTTP" )

	do case
	case cOpc = "A"
		ohttp:Open( "POST" ,cUrlSkualo, .F. )
	case cOpc = "M"
		ohttp:Open( 'PUT' ,cUrlSkualo, .F. )
	case cOpc = "L"
		ohttp:Open( 'GET' ,cUrlSkualo, .F. )
	otherwise
		MsgInfo( "Debe enviar Opcion " )
		return("")
endcase

if cFuncion $ "DTE;PDF"
	oHttp:SetRequestHeader("accept", "application/pdf" )
else
	oHttp:SetRequestHeader("accept", "application/json" )
	if cOpc <> "L"
		oHttp:SetRequestHeader("content-type", "application/json" )
	endif
endif

oHttp:SetRequestHeader("Authorization", "Bearer " + _TOKENEMP_ )

TRY
  oHttp:Send( jSon )
CATCH
  lOk := .f.
END

if lOk .and. oHttp:status = 200

	hb_jsonDecode( oHttp:ResponseText,@hReturn )

	if cFuncion = "GETPDF"
		cFilePdf := DRIVELOCAL+'\TEMPORAL\'+cPdf+'.pdf'
		//cPdf = tip_doc + num_doc

		hb_memowrit( cFilePdf, oHttp:ResponseBody )

		if left( cPdf,3) = "BEL"
			cPrinter := ViewUsu():Bel
		else
			cPrinter := ViewUsu():Fel
		endif

		if empty( cPrinter )
			cCmd := cSumatra + " "+cFilePdf
		else
			cCmd := cSumatra + ' -Print-to "' + alltrim( StrToken( cPrinter, 1, "," ) ) + '" -exit-on-print ' + cFilePdf
		endif

		MsgRun( "Imprimiendo archivo "+cFilePdf, "Espere..", { || winexec( cCmd, SW_HIDE )  } )

	else
		//hb_jsonDecode( oHttp:ResponseText,@hReturn )

		hReturn["status"]   	 := 200
		hReturn["statusText"] := "ok"
		hReturn["title"]   	 := "ok"
		hReturn["isError"]    := .f.
	endif

else
	if lOk // hizo la conexion pero skualo rechazo la solicitud
		hb_jsonDecode( oHttp:ResponseText,@hReturn )
		hReturn["status"]   	  := oHttp:status
		hReturn["statusText"]  := oHttp:statusText
		hReturn["title"]   	  := lower(hReturn["title"])
		hReturn["ErrorSkualo"] :=  {strtran(oHttp:ResponseText, ",", ","+CRLF ) }
		hReturn["JsonSkualo"]  :=  { json }
		hReturn["isError"]    := .t.
	else
		hReturn["status"]   	  := 400
		hReturn["title"]   	  := "error"
		hReturn["statusText"]  := "Error en la comunicación con Skualo"+CRLF+"hay q volver hacer la operación"
		hReturn["ErrorSkualo"] :=  {""}
		hReturn["JsonSkualo"]  :=  { json }
		hReturn["isError"]    := .t.
	endif
endif

return( hReturn )
//-----------------------------------------------------------------------------------------------------
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl

Continue the discussion