Печать на принтер этикеток с веб-сайта / веб-приложения? - PullRequest
33 голосов
/ 03 ноября 2010

Существуют ли какие-либо известные принтеры этикеток, которые будут принимать команды печати с веб-сайта или веб-приложения?

В частности, одноразовые принтеры этикеток, такие как Dymo, Brother, Zebra и т. Д.

Кто-нибудь имел успех в печати на этих принтерах (без использования взлома только для Internet Explorer или элемента управления ActiveX)

Я бы подумал, что, в конце концов, должно быть решение, когда мы перейдем к болеемир, ориентированный на браузер.

Ответы [ 7 ]

29 голосов
/ 20 января 2015

Ничего себе.Я знаю, что об этом спрашивали более 4 лет назад, но, потратив большую часть недели на поиски надежного способа печати этикеток из веб-приложения, мне пришлось озвучить здесь.

Вот что ямы нашли:

  • DYMO кажется наиболее вероятным кандидатом на превосходство.Но нет, оказывается, он печатает только из (а) своего собственного приложения или (б) чего-то, используя свой SDK.DYMO SDK использует модель чертежа XML, которая является слишком сложной и ограниченной по макету и стилю.Документация разбросана и непонятна (например, каковы <Bounds> значения для общих размеров меток? Там нет описания параметров тега где-либо!) Так расстраивает, так разочаровывает.

  • Есть qz (был jzebra) , который позволяет выполнять браузерную печать для устройств, говорящих на EPL, ZPL, FGL, ESC / POS, EPCL и CPCL ..., включая серию Zebra.Требуется загрузка интеграции (запуск веб-сервера на устройстве, к которому подключен принтер этикеток), но он работает.

  • Существует хорошо разработанное стороннее приложение от Peninsula , который работает для DYMO (среди прочих), но требует среднего шага печати из браузера в PDF.Они также предполагают, что вы никогда не будете масштабировать то, что вы хотите, распечатав менее 70%, что неверно.

ОП говорит: «Я бы подумал, что в конечном итоге придетсярешение, поскольку мы движемся в более ориентированный на браузер мир ".Четыре года спустя я бы пошел дальше и предположил, что любой принтер этикеток, который не может печатать через браузер (или просто ведет себя как обычный принтер с небольшой бумагой), ОСТАЕТСЯ В ПУТИ от своего потенциала.Макет в HTML + CSS совсем несложно.Браузеры отлично разбирают его и отображают в любом разрешении на любом устройстве вывода.Это кажется таким очевидным.

Если кто-нибудь знает о термопринтере для печати этикеток, который печатает из браузера, а не заключает вас в тюрьму по методологии архаичной интеграции, я бы очень хотел знать!

9 голосов
/ 08 сентября 2011

У принтеров Dymo есть плагин для браузера, который позволяет печатать из javascript . Очень прост в использовании.

Возвращаясь к этому вопросу несколько лет спустя.

Сетевые принтеры Zebra просты в печати. В одном проекте у меня было веб-приложение, открывающее сокет к принтеру и подающее ему инструкции в ZPL.

6 голосов
/ 07 мая 2015

Вы также можете попробовать PrintNode , который предоставляет решение для облачной печати и означает, что вы можете печатать прямо на любом принтере через Интернет.

4 голосов
/ 03 ноября 2010

Кросс-браузерный / совместимый с платформой скрипт веб-страницы / веб-страницы не имеет низкоуровневого доступа, необходимого для передачи на принтер команды языка принтера (такой как Zebra Printer Language [ZPL]).Для этого требуется элемент управления ActiveX / плагин браузера / апплет / подобный бит исполняемого кода.Это ограничение не относится к конкретному принтеру, оно исходит от браузера, а не от производителя принтера.

Однако многие принтеры этикеток позволяют печатать на них так, как если бы они были обычными принтерами - только те, которые печатают очень мелкими частямибумаги.Вы можете разместить свой ярлык с помощью HTML / CSS.При отображении результатов попросите пользователя перейти в «Файл> Печать» и выбрать принтер этикеток, прежде чем нажимать «Печать».

Надеюсь, это поможет,
Бен

1 голос
/ 03 февраля 2017

У Zebra теперь есть инструмент под названием BrowserPrint, который работает как PrintNode специально для принтеров Zebra.(в отличие от Printnode, его можно использовать с принтерами Zebra)

На некоторых принтерах также есть ppd-файлы, и / или они могут быть сконфигурированы в чашках в системе на платформе linux или иным образом подключены и разговаривают через linux.(что означает, что для печати на нем невозможно использовать что-то из сценариев оболочки, php, perl или других методов, создав простой демон сервера или настроив что-то вроде apache или lighttpd на Linux-коробке или даже на raspberry pi, подключенном кпринтер)

0 голосов
/ 23 мая 2017
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Management;
using System.Reflection;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        GetAllPrinterList();
        this.textBox1.Attributes.Add(
    "onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");
        this.lstPrinterList.Attributes.Add(
    "onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");

    }

    private void GetAllPrinterList()
    {
        //ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
        //objScope.Connect();

        //SelectQuery selectQuery = new SelectQuery();
        //selectQuery.QueryString = "Select * from win32_Printer";
        //ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
        //ManagementObjectCollection MOC = MOS.Get();
        //foreach (ManagementObject mo in MOC)
        //{
        //    lstPrinterList.Items.Add(mo["Name"].ToString());
        //    //lstPrinterList.Items.Add(new ListItem(mo["Name"].ToString()));

        //}

        lstPrinterList.Items.Add("\\\\10.32.65.6\\Parcel-Zebra-FDX ZM400");
        lstPrinterList.Items.Add("\\\\10.32.65.4\\Singles_Station_Z_Printer");
        lstPrinterList.Items.Add("\\\\10.32.65.12\\ZebraZ4M-Packaging");
        if (lstPrinterList.Items.Count > 3)
        {
        lstPrinterList.Items.RemoveAt(5);
        lstPrinterList.Items.RemoveAt(4);
        lstPrinterList.Items.RemoveAt(3);

        }

        //LocalPrintServer printServer = new LocalPrintServer();
        //string printer;
        //printer = LocalPrintServer.DefaultPrintQueue;
        //System.Management.ObjectQuery oquery =
        //        new System.Management.ObjectQuery("SELECT * FROM Win32_Printer");

        //    System.Management.ManagementObjectSearcher mosearcher =
        //        new System.Management.ManagementObjectSearcher(oquery);

        //    System.Management.ManagementObjectCollection moc = mosearcher.Get();

        //    foreach (ManagementObject mo in moc)
        //    {
        //        System.Management.PropertyDataCollection pdc = mo.Properties;
        //        foreach (System.Management.PropertyData pd in pdc)
        //        {
        //           // if ((bool)mo["Network"])
        //           // {
        //                lstPrinterList.Items.Add(mo["Name"].ToString());
        //           // }
        //        }
        //    }

        //}
        //        using (var printServer = new PrintServer(string.Format(@"\\{0}", PrinterServerName)))
        //{
        //    foreach (var queue in printServer.GetPrintQueues())
        //    {
        //        if (!queue.IsShared)
        //        {
        //            continue;
        //        }
        //        Debug.WriteLine(queue.Name);
        //     }
        // }
        //foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
        //{
        //MessageBox.Show(printer);
        //System.Web.UI.WebControls.ListBox lstPrinterList = new System.Web.UI.WebControls.ListBox();
        //System.Web.UI.WebControls.ListBox lstPrinterList = (System.Web.UI.WebControls.ListBox)Page.FindControl("lstPrinterList");
        //lstPrinterList.Text = "Zebra 110PAX4 (203 ;dpi)";

        //lstPrinterList.Items.Add(printer.ToString());
        //lstPrinterList.Items.Add(new ListItem(printer));
        //lstPrinterList.Items.Add(printer);
        //System.Web.UI.WebControls.ListBox lstPrinterList = (System.Web.UI.WebControls.ListBox)Page.FindControl("ListBox1");
        //Zebra 110PAX4 (203 dpi)
        //lstPrinterList.Items.Insert(printer);
        //}
    }


    //private void lstPrinterList_OnClick(object sender, System.EventArgs e)
    //{
    //    // Get the currently selected item in the ListBox.
    //    string curItem = lstPrinterList.SelectedItem.ToString();

    //    // Find the string in ListBox2.
    //    int index = lstPrinterList.DataTextField(curItem);
    //    //int index = lstPrinterList.FindString(curItem);
    //    //lstPrinterList.DataTextField(curItem);
    //    // If the item was not found in ListBox 2 display a message box, otherwise select it in ListBox2.
    //    if (index == -1)
    //        MessageBox.Show("Item is not available in ListBox2");
    //    else
    //        lstPrinterList.SetSelected(index, true);
    //}

    //private void button1_Click(object sender, System.EventArgs e)
    //{

    //    string str = File.ReadAllText("lpn.prn");
    //    str = str.Replace("BOX_TYPE", "boom");
    //    str = str.Replace("11111111", textBox1.Text);
    //    File.WriteAllText("lpn.prn", str);
    //            // Print the file to the printer.
    // RawPrinterHelper.SendFileToPrinter("\\\\Zebra-FDX ZM400 200 dpi (ZPL)", "C:\\Users\\Administrator\\Documents\\Visual Studio 2015\\Projects\\WindowsFormsApplication4\\Prn Print\\bin\\Debug\\lpn.prn");  
    //}

    public void button1_Click(object sender, System.EventArgs e)
    {
        String prnFile = "lpn2.prn";
        string s = File.ReadAllText(prnFile);
        string printer;
        String Printer = lstPrinterList.SelectedItem.ToString();
        s = s.Replace("*description*", "snuffles");
        s = s.Replace("*barcode*", textBox1.Text);
        //File.WriteAllText("PPlpn.prn", s);
        //s = "^XA^LH30,30\n^FO20,10^ADN,90,50^AD^FDHello World^FS\n^XZ";
        printer = lstPrinterList.SelectedItem.Value;
        PrintDialog pd = new PrintDialog();
        pd.PrinterSettings = new PrinterSettings();
        RawPrinterHelper.SendStringToPrinter(printer, s); 
        //RawPrinterHelper.SendStringToPrinter(Printer, s);
        //Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, "?__VIEWSTATE=%2%3D&ctl00%24MainContent%24textBox1=bp300&ctl00%24MainContent%24lstPrinterList=Shipping+Printer"));




    }
    protected void textBox1_TextChanged(object sender, EventArgs e)
    {

    }
}




public class RawPrinterHelper
{
    // Structure and API declarions:
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false; // Assume failure unless you specifically succeed.
        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";

        // Open the printer.
        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            // Start a document.
            if (StartDocPrinter(hPrinter, 1, di))
            {
                // Start a page.
                if (StartPagePrinter(hPrinter))
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }

    public static bool SendFileToPrinter(string szPrinterName, string szFileName)
    {
        // Open the file.
        FileStream fs = new FileStream(szFileName, FileMode.Open);
        // Create a BinaryReader on the file.
        BinaryReader br = new BinaryReader(fs);
        // Dim an array of bytes big enough to hold the file's contents.
        Byte[] bytes = new Byte[fs.Length];
        bool bSuccess = false;
        // Your unmanaged pointer.
        IntPtr pUnmanagedBytes = new IntPtr(0);
        int nLength;

        nLength = Convert.ToInt32(fs.Length);
        // Read the contents of the file into the array.
        bytes = br.ReadBytes(nLength);
        // Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
        // Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
        // Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
        // Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes);
        return bSuccess;
    }

    public static bool SendStringToPrinter(string szPrinterName, string szString)
    {
        IntPtr pBytes;
        Int32 dwCount;
        // How many characters are in the string?
        dwCount = szString.Length;
        // Assume that the printer is expecting ANSI text, and then convert
        // the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString);
        // Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount);
        Marshal.FreeCoTaskMem(pBytes);
        return true;
    }
}

Это то, что я создал в C #, и это отлично сработало. Это веб-приложение.

0 голосов
/ 03 ноября 2010

Вы можете печатать из подписанного Java-апплета или из Java Web Start приложения:

http://java.sun.com/javase/technologies/desktop/printing/

Это должно сработать, если вы отформатируете вывод для печати так, чтобы он помещался на этикетках.

Обратите внимание, что большинство современных браузеров ограничивают поддержку апплетов Java, поэтому у вас могут возникнуть проблемы с апплетом, в зависимости от используемых браузеров. В частности, Google Chrome прекратит поддержку Java-апплетов в сентябре 2015 года . Эти ограничения не применяются к Java Web Start, который должен продолжать работать.

...